簡體   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