1

该程序完美运行:

#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;
}

但为了以后方便,我想把malloc部分放在tempfunction. 当我这样做时,我得到一个分段错误错误。

我认为这可能是由于初始化,所以char **comments;我不写:

char a = 'a';
char *P = &a;
char **comments = &P;

但是,它仍然不起作用。如果您能帮助我理解为什么会发生这种情况以及如何解决它,我将不胜感激。

4

3 回答 3

2

尝试:

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);

当然你必须在最后释放以避免内存泄漏

于 2013-07-10T12:23:02.687 回答
0

如果要comments在函数内部进行更改,则必须传递它的地址,以便正确反映它。所以你需要将&commentsie传递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;
}
于 2013-07-10T12:13:20.473 回答
-2

不要从主函数传递 char **comments,而不是这样做,您可以在 tempfunction 中声明 char **comments,然后将注释的引用返回给主函数。它会起作用的。

于 2013-07-10T12:00:37.717 回答