函数中的malloc—;分割误差
该程序运行良好:函数中的malloc—;分割误差,c,malloc,C,Malloc,该程序运行良好: #include <stdio.h> #include <stdlib.h> #include <string.h> #define MAX_NUM 2 int tempfunction (char **comments) { char str1[]="First string\n"; char str2[]="This is the second string\n"; *(comments+0)=(char *
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_NUM 2
int tempfunction (char **comments)
{
char str1[]="First string\n";
char str2[]="This is the second string\n";
*(comments+0)=(char *) malloc(strlen(str1)+1);
*(comments+1)=(char *) malloc(strlen(str2)+1);
strcpy(*(comments+0), str1);
strcpy(*(comments+1), str2);
return 0;
}
int main(void)
{
char **comments;
/* This is the section I am talking about */
comments=(char **) malloc(MAX_NUM*sizeof(char *));
if (comments==NULL)
{
printf("\n### ERROR: malloc failed.\n");
exit(EXIT_FAILURE);
}
/* Upto here............................. */
tempfunction(comments);
printf("%s%s", comments[0], comments[1]);
return 0;
}
但是,它仍然不起作用。如果您能帮助我理解为什么会发生这种情况以及如何解决,我将非常感激 不要从主函数传递char**注释,
不必这样做,您可以在tempfunction内声明char**comments,然后将注释引用返回到main函数。它会起作用。如果您想在函数中更改
注释,您必须传递它的地址,以便适当地反映它。因此,您需要将&注释
即char***
传递到tempfunction()
我建议将代码更新为:
int tempfunction (char ***ref_comments)
{
char str1[]="First string\n";
char str2[]="This is the second string\n";
char **comments = malloc(MAX_NUM*sizeof(char *));
*(comments+0)=(char *) malloc(strlen(str1)+1);
*(comments+1)=(char *) malloc(strlen(str2)+1);
strcpy(*(comments+0), str1);
strcpy(*(comments+1), str2);
//now update the passed variable
*nef_comments = comments;
return 0;
}
int main(void)
{
char **comments;
/* This is the section I am talking about */
comments=(char **) malloc(MAX_NUM*sizeof(char *));
if (comments==NULL)
{
printf("\n### ERROR: malloc failed.\n");
exit(EXIT_FAILURE);
}
/* Upto here............................. */
// pass address of comments
tempfunction(&comments);
printf("%s%s", comments[0], comments[1]);
return 0;
}
尝试:
你这样称呼它:
tempfunction(&comments);
当然,为了避免内存泄漏,您必须在最后释放内存<代码>字符*注释[2]={NULL,NULL}代码>will do.H2CO3,devnull:谢谢,我理解,但是对于这个特殊问题,当节位于main()中时,它可以完美地工作。所以铸造不是问题!谢谢,但问题是我不知道现在有多少评论!谢谢,但我不想返回任何内容(0或1除外),因为此函数还有很多事情要做。而且您正在创建内存泄漏。@Armin他想通过分配它来更改它。我想剪切指定的部分并将其放入tempfunction中。所以下次我想要这个函数时,我只需要做一个定义。非常感谢,它工作正常。只是为了确保:要检查malloc的输出,我必须执行“if(*comments==NULL)”,对吗?是的,与您在主函数中执行的操作相同;)
int tempfunction (char ***comments)
{
char str1[]="First string\n";
char str2[]="This is the second string\n";
*comments = malloc(MAX_NUM * sizeof(**comments)); /* you must check the return of malloc */
(*comments)[0] = strdup(str1);
(*comments)[1] = strdup(str2);
return 0;
}
tempfunction(&comments);