gpt4 book ai didi

c - 为什么退出循环后数组中的值会发生变化?

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

由于某种原因退出 while 循环后,数组中的值发生了变化,但我不知道为什么。在循环内,值是正确的,并且它们通常存储在数组 (a) 内。这是在 c 中!

int * readFile()
{
char file_name[50];
printf("Enter the name of the file to open:\n");
scanf("%s",file_name);
FILE *fp;
fp = fopen(file_name,"r");

if(fp == NULL )
{
printf("Sorry but the File you entered cannot be opened\n");
int *b;
b[0] = -1;
return b;
}

int *a;
int j=0;
long int value=0;
while (fscanf(fp,"%d",&value)!=EOF) {
if((a =malloc(sizeof(long int))) == NULL)
printf("not enough memory\n");
a[j]=value;
j++;
}
printf("%d %d %d\n",a[0],a[1],a[2]);
int i=0;
for(i=0; i<j;i++)
{
printf("array[%d] = %d\n",i,a[i]);
}
fclose(fp);
return a;
}

任何帮助将不胜感激!

最佳答案

当您执行 if((a =malloc(sizeof(long int))) == NULL) 时,您仅为单个 long int (大小为 32 位)分配足够的内存,但是您需要为计划存储的每个 int 分配内存。因为malloc分配的是单 block 内存,所以你需要事先知道你打算存储多少个int。如果您不介意开销,您可以对正在读取的文件进行初步运行并计算您将读取的整数数量(基本上是您的 j 变量),然后您可以执行

a =malloc( intCounter * sizeof(long int))) == NULL ,其中 intCounter 是文件 (j) 中的整数总数。

另一种选择是使用链表(这与您尝试做的很接近),您可以在其中为每个 int 动态分配内存,但您需要将指针信息存储到链表中的下一个节点数组。

while 循环中的 malloc 调用会覆盖 Int 的单次分配中存储的数据。例如,如果您从文本文件中读取 1 2 3,它将在 a 中存储 1,malloc 与 a 不同的内存地址,存储 2,malloc 另一个内存地址并存储 3。导致打印 0 , 0 , 3 。

关于c - 为什么退出循环后数组中的值会发生变化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28162175/

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