c - 输入文件中数组字符串的动态内存分配

标签 c dynamic-memory-allocation

我是一个相对较新的 C 程序员,我试图简单地将输入文件中的内容打印到我的屏幕上。我必须使用动态内存分配,我面临的问题是,如果我的字符串中的字母数大于 8,它会覆盖它。

int main(){
FILE *input = fopen("inpit.txt","r");
int b;
char **aPtr;
int i = 0;
int j = 0;
fscanf(input,"%d",&b); //takes first value from input file which tells me number of strings in the file
aPtr = (char **)malloc(sizeof(char *)*b); 
for(i=0;i<b;i++) {
    aPtr[i]=(char *)malloc(sizeof(char));
}
for(i = 0;i < b;i++){
    fscanf(input,"%s",&aPtr[i]);
}
for(i = 0;i < b;i++){
    printf("Address %d = %d\n",i,&aPtr[i]);
}

for(i = 0;i < b;i++){
    printf("%s\n",(aPtr+i));
}
return 0; }
我对文件 inpit1.txt 的输入是:
5
grapefruit
apple
Banana
monkey
orange
如果我运行文件。除了葡萄柚,一切都会打印出来。这将被覆盖为葡萄柚。
任何帮助,将不胜感激。先感谢您。

最佳答案

我看到的问题:

  • 您没有为 aPtr[i] 分配足够的内存.
    aPtr[i]=(char *)malloc(sizeof(char));
    

    只为一个 char 分配内存.拿着一根绳子是不够的。你需要这样的东西:
    int arraySize = 20; // Make it large enough
    aPtr[i] = malloc(arraySize); // No need to use sizeof(char).
                                 // It is always 1
    
  • 确保在读取字符串时不会溢出数组大小。代替:
    fscanf(input,"%s",&aPtr[i]);
    

    用:
    fscanf(input,"%19s", aPtr[i]);
    //                  ^^^ Remove the & operator. That is wrong.
    //            ^^^ Add size to prevent overflow.
    
  • 您对 printf 使用了错误的参数功能。代替:
    printf("%s\n",(aPtr+i));
    


    printf("%s\n", *(aPtr+i));
    //            ^^^ Missing pointer dereferencing operator
    

    或者
    printf("%s\n", aPtr[i]);
    
  • 关于c - 输入文件中数组字符串的动态内存分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33509994/

    相关文章:

    c - Linux 堆碎片

    c - 为什么会出现错误 "segmentation fault"?

    c - c中释放指针后如何保存指针地址

    c++ - 动态内存分配

    无法理解从 C 到汇编的这种转换

    c - 您是否需要为 C 中的结构中的函数指针分配空间?

    c - 大型动态数组中未使用的内存会怎样?

    c - C语言程序计算重复单词数

    c - C 中的文件系统 VS 原始磁盘基准测试

    c - luaL_openlib 替代 Lua 5.2