简体   繁体   English

Malloc 动态数组大小导致分段错误

[英]Malloc dynamic array size causes segmentation fault

My goal is to have a an array of arrays so I can get the size from another variable and append as many objects as I need in a for loop later.我的目标是拥有一个 arrays 数组,这样我就可以从另一个变量和 append 中获取所需的对象数量,以便稍后在 for 循环中使用。

Sorta like this:像这样排序:

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

Right now you have 4D char array.现在你有 4D 字符数组。 The following code is sufficient for your data.There is no point of extra dimension if size of that dimension is one.以下代码足以满足您的数据。如果该维度的大小为 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]);

Edited:编辑:

Following is for char* test[NumElement] .以下是char* test[NumElement] Similarly you can implement for 3d array.同样,您可以实现 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
}

Edited2: exact code编辑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