我正在尝试从文件中读取数据以将其前n个元素存储在数组中。数据是整数序列:
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, ...
当我检查数组的内容时,我找不到正确的值,好像是保存了正确值的地址(?)?
这是我的代码:
FILE* ifp;
ifp = fopen ("input.txt", "r");
int n = 10;
int* readbuf;
readbuf = (int *) malloc (n * sizeof(int));
for (int i=0; i<n; i++){
int j = 0;
fscanf (ifp, "%d", &j);
j = readbuf[i];
printf ("\n j = %d and readbuf = %d", j, readbuf[i]);
}
fclose(ifp);
如果输入文件包含以下序列,代码是否会有所不同:
0
1
2
3
...
答案 0 :(得分:3)
这应该解决它:
readbuf[i] = j;
而不是
j = readbuf[i];