c - C中指向指针和realloc的指针

标签 c pointers

您好,我的问题是,我在 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/

相关文章:

c - 卡在计算 DNF 最高出现次数上

C++ 风格的 vector - 指针数组还是数组?

unit-testing - UIApplication.sharedApplication().delegate 作为 AppDelegate 导致 EXC_BAD_ACCESS 在快速单元测试中使用它

c - 指向函数的 Typedef 结构指针 (C)

c - 如何使用 C 获得类似于 Linux top 的输出

c - 如何使用 VC++ 编译器刷新 .C 程序中的标准输入设备?

c++ - 一组 LPWSTR 指针,不能正常工作

c++ - 错误 C2512 'DerivedClass' : no appropriate default constructor available

ios - 将表示十六进制值的 NSString 转换为十六进制( @"0d"到 0x0d)

c - strcmp 有问题吗?