您好,我的问题是,我在 while 循环中分配给指向指针数组的指针的值在循环中显示正常,但在循环后丢失,例如读取一个包含五个记录的文件(为测试保留这个缩写)输出以下内容- 我显然不理解这里的一些基本知识,并且在这里和其他地方阅读了数十篇帮助文章,但他们解决的问题在我看来并不相关。谁能帮帮我吗?我知道我没有进行正确的错误处理,我从一个更大的程序中剥离了这段代码,以尽可能地尝试隔离问题。
Program debug output
list[0] = Test Record 1
list[1] = Test Record 2
list[2] = Test Record 3
list[3] = Test Record 4
list[4] = Test Record 5
In main list[0] = Test Record 5
In main list[1] = Test Record 5
In main list[2] = Test Record 5
In main list[3] = Test Record 5
In main list[4] = Test Record 5
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define RECLEN 500
FILE *infil;
char *input;
char *p1;
char buf[RECLEN];
char hold[RECLEN];
char **list;
int c;
long arrcnt;
int readin(void);
void main(argc,argv)
int argc;
char *argv[];
{
if(argc < 2)
{
printf("%s: No filename specified\n",argv[0]);
exit(1);
}
input = argv[1];
if((infil = fopen(input,"r")) == NULL)
{
printf("Error on opening file %s\n",input);
exit(1);
}
arrcnt=0;
readin();
while(feof(infil) == 0)
{
list = realloc(list, (arrcnt+1) * sizeof(char *));
strcpy(hold,buf);
list[arrcnt] = hold;
printf("list[%d] = %s",arrcnt,list[arrcnt]);
arrcnt++;
readin();
}
for (c = 0; c < 5;c++)
{
printf("In main list[%d] = %s",c,list[c]);
}
fclose(infil);
return (0);
}
int readin()
{
int j;
for(j=0;j<RECLEN;j++)
{
buf[j] = '\0';
}
fgets(buf,RECLEN,infil);
p1=buf;
return 0;
}
最佳答案
strcpy(hold,buf); list[arrcnt] = hold;
在这里,您将指针 list[arrcnt]
分配给数组的开头
hold
,它的内容将是最后放入其中的最后一个东西。
您想要的是让列表的每个元素指向一个不同的 char[]
数组。您可以改为这样做:
list[arrcnt] = malloc(strlen(buf)+1);
strcpy(list[arrcnt], buf]);
关于c - C中指向指针和realloc的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38544846/