繁体   English   中英

C程序:尝试填充动态创建的数组时出现分段错误

[英]C program: segmentation fault when trying to populate dynamically created array

我正在做一项作业,要求创建一个动态分配的数组,该数组将使用文本文件中的字符串填充。 然后,我需要将数组打印到标准输出,将数组随机播放,然后再次打印。

我当前的问题是,在没有分割错误的情况下,似乎无法用任何东西填充数组。 我使用静态数组测试了该程序,并且一切正常,因此我知道其他任何代码都没有问题。

这是我程序的一部分。

void alloc2dArray(char ***source, int dim1, int dim2)
{
    int i = 0;

    source = malloc(sizeof(char *) * dim1);

    if(source == NULL) 
    { 
        printf("Memory full!");
        exit(EXIT_FAILURE);
    }
    for(i = 0; i < dim1; i++)
    {
            source[i] = malloc(sizeof(char) * (dim2 + 1));
            if(source[i] == NULL) 
        { 
            printf("Memory full!"); 
            exit(EXIT_FAILURE);
        }
    }
}

编辑:

为了避免成为三星级程序员,我将代码更改为以下代码段。 幸运的是,这解决了我的问题。 因此,感谢Kniggug将链接发布到了我以前不知道的地方。

char** alloc2dArray(int dim1, int dim2)
{
        int i = 0;

        char **twoDArray = malloc(sizeof(char *) * dim1);

        if(twoDArray == NULL)
        {
                printf("Memory full!");
                exit(EXIT_FAILURE);
        }
        for(i = 0; i < dim1; i++)
        {
                (twoDArray[i]) = malloc(sizeof(char) * (dim2 + 1));
                if(twoDArray[i] == NULL)
                {
                        printf("Memory full!");
                        exit(EXIT_FAILURE);
                }
        }

        return twoDArray;
}

谢谢。

Void alloc2dArray(char ***source, int dim1, int dim2)
{
    int i = 0;

    source = malloc(sizeof(char *) * dim1);

上面的分配除了泄漏内存外,在此功能之外没有任何作用。 您的意思是:

    *source = malloc(sizeof(char *) * dim1);

类似地:

(*source)[i] = malloc(sizeof(char) * (dim2 + 1));

更改source(*source)alloc2dArray

Void alloc2dArray(char ***source, int dim1, int dim2)
{
    int i = 0;

    *source = malloc(sizeof(char *) * dim1);

    if(*source == NULL)
    {
        printf("Memory full!");
        exit(EXIT_FAILURE);
    }
    for(i = 0; i < dim1; i++)
    {
        (*source)[i] = malloc(sizeof(char) * (dim2 + 1));
        if((*source)[i] == NULL)
        {
                printf("Memory full!");
                exit(EXIT_FAILURE);
        }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM