簡體   English   中英

Malloc 動態數組大小導致分段錯誤

[英]Malloc dynamic array size causes segmentation fault

我的目標是擁有一個 arrays 數組,這樣我就可以從另一個變量和 append 中獲取所需的對象數量,以便稍后在 for 循環中使用。

像這樣排序:

char *test[3][1][3] = {
    {"FOO", "BAR"},
    {"BIZ", "NIZ"},
    {"BIZ", "NIZ", "NAZ"}
};

    
printf("\nTESTNG: \n");
printf("TEST: %s\n", test[0][0][0]);
printf("TEST: %s\n", test[0][0][1]);
// this is the only value that is dynamic, the rest are key value pairs that are being inserted
// like FOO : BAR
// this function returns an integer
int array_size = someotherfunction();

char** people = (char**) malloc(array_size);
for(i = 0; i < array_size; i++){
        people[i] = (char*)malloc(2);
}
people[0][0][0] = "FOO";
printf("Person: %s", people[0][0][0]);

現在你有 4D 字符數組。 以下代碼足以滿足您的數據。如果該維度的大小為 1,則沒有額外維度的意義。

    char *test[3][3] = {
        {"FOO", "BAR"},
        {"BIZ", "NIZ"},
        {"BIZ", "NIZ", "NAZ"}
    };
printf("TEST: %s\n", test[0][0]);
printf("TEST: %s\n", test[0][1]);

編輯:

以下是char* test[NumElement] 同樣,您可以實現 3d 陣列。

char **test = malloc(sizeof(char*) * NumElement);
for (i = 0; i < NumElement; i++)
{
    test[i] = malloc((STR_Length+1)* sizeof(char));  //for "FOO" STR_Length is 3, +1 for null char
}

編輯2:確切的代碼

int N = 3, M = 3, STRLEN=3;
char *** test = (char *** )malloc(N * sizeof(char ** )) ;  //equal to char * test[N][M]
for(int i = 0 ; i < N ; i++ ) //Allocate memroy for each row
{ 
    test[i] = (char ** ) malloc(M * sizeof(char * )) ;
    for ( int j = 0 ; j < M ; j++ )
    { 
        test[i][j] = (char *) malloc ((STRLEN+1) * sizeof(char));
    }
 }
 test[0][0] = "FOO";
 test[0][1] = "BAR" ;
 printf("%s\n",test[0][0]);
 printf("%s\n",test[0][1]);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM