Allocate memory to char *** in C

前端 未结 3 1079
悲&欢浪女
悲&欢浪女 2020-12-07 03:32

So, I\'m having trouble in allocating memory for a char *** type variable. My objective is to create a matrix of strings and the code I currently have for memor

3条回答
  •  情歌与酒
    2020-12-07 03:45

    As you have said, you were able to successfully create an array of strings using your below code:

    char **list;
    list = calloc(n, sizeof(char *));
    for (j = 0; j < n; j++){
    list[j] = calloc(MAX_STR, sizeof(char));
    }
    

    Now, you need an array of array of strings, so it should be:

    char ***matrix;
    
    matrix = calloc(n, sizeof(char**)); //This creates space for storing the address of 'n' array of strings 
    for(z = 0; z < n; z++) { //This loop creates the 'n' array of strings.
        matrix[z] = calloc(n, sizeof(char*));
        for(i = 0; i < n; i++) {
            matrix[z][i] = calloc(MAX_STR, sizeof(char));
        }
    }
    

    So, basically, in the second code, you are just creating space for storing 'n' lists. Hope this makes it clear.

提交回复
热议问题