gpt4 book ai didi

C - 数组在放入变量时从同一元素返回不同的值

转载 作者:行者123 更新时间:2023-11-30 19:24:46 24 4
gpt4 key购买 nike

我对编程很陌生。简而言之,我的问题是:

arr[0]=1 arr[1]=2 arr[2]= -4
printf("\n Element 0 when in array: %d\n", arr[0]); // Prints 1 as it should
arr[0] = a;
printf(" Element 0 assigned to variable a: %d", a); /* Prints 67 ?? (Elements 1 and 2
are printed as 0 when assigned different variables.) */

我希望我的“a”变量返回与 arr[0] 相同的值(然后为 arr[1] 和 arr[2] 的另外两个变量执行此操作)

我有一个名为“Dane.txt”的文本文件,其中包含一些数字,其内容为“1, 2, -4,”。

下面是我尝试使用从 .txt 文件获取的输入来解决数学问题的完整代码(大部分内容是从 here 获取的):

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[]){

// Initializing the file pointer
FILE *fs;

char ch, buffer[32];
int i = 0, arr[100], j = 0;
int a, b, c, arr2[3];

// Openning the file with file handler as fs
fs = fopen("Dane.txt", "r"); // "Dane.txt" contents: 1, 2, -4,

// Read the file unless the file encounters an EOF
while(1){
// Reads the character where the seeker is currently
ch = fgetc(fs);

// If EOF is encountered then break out of the while loop
if(ch == EOF){
break;
}

// If the delimiter is encounterd(which can be
// anything according to your wish) then skip the character
// and store the last read array of characters in
// an integer array
else if(ch == ','){

// Converting the content of the buffer into
// an array position
arr[j] = atoi(buffer);

// Incrementing the array position
j++;

// Clearing the buffer, this function takes two
// arguments, one is a character pointer and
// the other one is the size of the character array
memset(buffer, 0, 32);

// clearing the counter which counts the number
// of character in each number used for reading
// into the buffer.
i = 0;

// then continue
continue;
}
else{

// reads the current character in the buffer
buffer[i] = ch;

// incrementing the counter so that the next
// character is read in the next position in
// the array of buffer
i++;
}
}
for(i = 0; i < j; i++){
arr2[i] = arr[i];
printf("Number [%d]: %d\n", i, arr[i]);
printf("%d\n", arr[i]);
}

printf("\n Element 0 when in array: %d\n", arr[0]); // Returns 1 as it should
arr[0] = a;
printf(" Element 0 assigned to variable a: %d", a); // Returns 67 ??
}

最佳答案

代码中没有任何地方可以为 a 分配任何值,因此当您打印 a 的值时,您会得到其中发生的任何垃圾内存区域。

arr[0] = a;

这是一项作业。左侧是分配给的变量arr[0]。右侧是分配给它的值。如果您对此不清楚,您可能希望学习一本好的 C 引用资料中有关左值和右值的部分。

关于C - 数组在放入变量时从同一元素返回不同的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59904999/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com