C中三维数组的问题

Problems in three dimension array in C

我这样定义了三维数组,但是它无法读取其中的任何字符串?问题出在哪里?谢谢!

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] 显示为空。

您应该对 3d "data" 数组使用 sizeof(char**),因为此 3d 数组的每个元素都是 char**。

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

您指定了无效的已分配对象大小。

你必须写

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

如果您的编译器支持可变长度数组,那么您只需调用一次 malloccalloc 即可分配所需的数组。例如

char ( *data )[courseTotal][20] = 
    malloc(  sizeof( char[stuTotal][courseTotal][20] ) );

char ( *data )[courseTotal][courceName] = 
    calloc(  1, sizeof( char[stuTotal][courseTotal][courceName] ) );

这是一个演示程序。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void) 
{
    size_t stuTotal = 5, courseTotal = 10, courceName = 20;

    char ( *data )[courseTotal][courceName] = 
        calloc(  1, sizeof( char[stuTotal][courseTotal][courceName] ) );


    strcpy(data[0][0],"hello");

    puts( data[0][0] );

    free( data );

    return 0;
}

它的输出是

hello

在这种情况下,要释放所有分配的内存,只需调用 free 一次。

当您分配外部数组而不是

时,您对 sizeof 的参数不正确
char ***data = (char***)calloc(stuTotal,sizeof(char));

需要

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

您可以大大简化该调用,如下所示:

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

同样

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

你不需要转换 malloccalloc 的结果,除非你在 C++ 中工作(在这种情况下你应该使用 new 或者,更好的是,某种容器类型)或 ancient C 实现(1989 年之前)。