我是一个相对较新的 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/