Search code examples
carraysstringpointerscalloc

Problems in three dimension array in C


I defined the three dimensional array like this, but I it can't read any string in it? Where is the problem? Thanks!

int stuTotal, courseTotal,i,k;//a dynamic array
printf("Input the total number of students that you would like to import:");
scanf("%d", &stuTotal);
printf("Input the total number of courses that you would like to import:");
scanf("%d", &courseTotal);

char ***data = (char***)calloc(stuTotal,sizeof(char));//data
for(i = 0;i < stuTotal;i++){
    data[i] = (char**)calloc(courseTotal,sizeof(char));
    for (k = 0;k < courseTotal;k++){
        data[i][k] = (char*)calloc(20,sizeof(char));
    }
}
strcpy(data[0][0],"hello");

data[0][0] is shown to be empty.


Solution

  • Your arguments to sizeof are incorrect when you allocate the outer arrays - instead of

    char ***data = (char***)calloc(stuTotal,sizeof(char));
    

    it needs to be

    char ***data = (char***)calloc(stuTotal,sizeof(char **)); // you're allocating N elements of type `char **`.
    

    You can greatly simplify that call as follows:

    char ***data = calloc( stuTotal, sizeof *data ); // sizeof *data == sizeof (char **)
    

    and similarly

    data[i] = calloc( courseTotal, sizeof *data[i] ); // sizeof *data[i] == sizeof (char *)
    

    You should not need to cast the result of malloc and calloc unless you're working in C++ (in which case you should be using new or, better yet, some kind of container type) or an ancient C implementation (pre-1989).