在 C 中创建一个二维字符串数组
Creating a 2D string array in C
所以基本上我试图从一个巨大的文本文件中读取数据,并且需要将数据存储在 2D
string
数组中 C
。但是我每次都得到 segmentation fault
。
这是我用来创建数组的代码:
Y = 3
X = 12
char ***some_array=NULL;
some_array = (char ***)malloc(Y * sizeof(char *));
for (int i=0; i<Y; i++)
for (int j=0; j<X; j++){
some_array[i] = (char **)malloc(X * sizeof(char *));
some_array[i][j] = (char *)malloc(16 * sizeof(char));
}
所以从技术上讲,我正在为此方法创建一个 3D 字符数组。我是不是做错了什么?
错误在你的循环中:
for (int i=0; i<Y; i++) {
some_array[i] = (char **)malloc(X * sizeof(char *));
for (int j=0; j<X; j++){
some_array[i][j] = (char *)malloc(16 * sizeof(char));
}
}
你应该在内部循环之外为 some_array[i]
分配内存。
您需要将 some_array[i] = (char **)malloc(X * sizeof(char *));
的分配从最内层循环移动到外层循环。而且,你should not cast the malloc return value。对于最终代码:
Y = 3
X = 12
char ***some_array = NULL;
some_array = malloc(Y * sizeof(char *));
for (int i = 0; i < Y; i++){
some_array[i] = malloc(X * sizeof(char *));
for (int j = 0; j < X; j++){
some_array[i][j] = malloc(16 * sizeof(char));
}
}
或者您可以创建一个静态分配的数组:
char some_array [X][Y][16];
所以基本上我试图从一个巨大的文本文件中读取数据,并且需要将数据存储在 2D
string
数组中 C
。但是我每次都得到 segmentation fault
。
这是我用来创建数组的代码:
Y = 3
X = 12
char ***some_array=NULL;
some_array = (char ***)malloc(Y * sizeof(char *));
for (int i=0; i<Y; i++)
for (int j=0; j<X; j++){
some_array[i] = (char **)malloc(X * sizeof(char *));
some_array[i][j] = (char *)malloc(16 * sizeof(char));
}
所以从技术上讲,我正在为此方法创建一个 3D 字符数组。我是不是做错了什么?
错误在你的循环中:
for (int i=0; i<Y; i++) {
some_array[i] = (char **)malloc(X * sizeof(char *));
for (int j=0; j<X; j++){
some_array[i][j] = (char *)malloc(16 * sizeof(char));
}
}
你应该在内部循环之外为 some_array[i]
分配内存。
您需要将 some_array[i] = (char **)malloc(X * sizeof(char *));
的分配从最内层循环移动到外层循环。而且,你should not cast the malloc return value。对于最终代码:
Y = 3
X = 12
char ***some_array = NULL;
some_array = malloc(Y * sizeof(char *));
for (int i = 0; i < Y; i++){
some_array[i] = malloc(X * sizeof(char *));
for (int j = 0; j < X; j++){
some_array[i][j] = malloc(16 * sizeof(char));
}
}
或者您可以创建一个静态分配的数组:
char some_array [X][Y][16];