【发布时间】:2018-05-23 06:40:14
【问题描述】:
嗨
我已经编写了这个程序,它创建了一个用户给出的书籍列表,我无法在程序结束时释放 my_value 并得到很多错误。
这是我的代码
#include <stdio.h>
#include <stdlib.h>
int main(){
int n;
printf("Please Enter the Number of Books:\n");
scanf("%d",&n);
char **array=(char *) malloc((n+1)*sizeof(char *));
for(int i=0;i<n;i++){
array[i] = (char *)malloc(sizeof(char *));
}
for(int i=0;i<n;i++){
char *my_value=(char *) malloc(sizeof(char)*100);
printf("Please Enter the Name of the %dth Book:\n",i+1);
scanf("%s",my_value);
*(array+i)=my_value;
free(my_value);
}
for(int i=0;i<n;i++){
printf("\n The Book Nr.%d is %s \n",i+1,*(array+i));
}
for(int i=0;i<n;i++){
free(array[i]);
}
free(array);
return 0 ;
}
【问题讨论】:
-
您遇到了什么样的错误?你在哪个平台上开发?你用过Valgrind吗?您应该显示一些示例数据并报告您从该示例数据中得到的错误。也许只有两本书的数据;这可能就足够了。请阅读有关如何创建 MCVE (minimal reproducible example) 的信息,注意数据和输出(实际与预期)都是 MCVE 的一部分。
-
你不需要转换
malloc的结果。见Do I cast the result of malloc?。此外,char **array=(char *) malloc((n+1)*sizeof(char *))具有不兼容的指针类型。