【发布时间】:2017-07-24 08:20:32
【问题描述】:
我想尝试一些 C 基础知识,因为我已经好几年没见过这种语言了。所以,我写了一个非常简单的程序,它分配一个二维数组,然后我想用一些值初始化它并打印它。
问题是 - 当我初始化元素 [0][0] 或 [0][1] 时,当我尝试打印第 4 行时程序崩溃。
你知道问题出在哪里吗?
我的代码(MWE)
#include <stdio.h>
#include <stdlib.h>
int main () {
int size = 5;
int** array_2d;
array_2d = (int**)malloc(sizeof(int)*size);
if(array_2d==NULL) exit(-1);
int i;
for (i = 0; i < size; i++){
array_2d[i] = (int*)malloc(sizeof(int)*size);;
printf("Allocated %d. column.\n", i);
}
int row, column;
for ( row = 0; row < size; row++) {
for( column = 0; column < size; column++) printf("%d ", array_2d[row][column]);
printf("\n");
}
array_2d[0][0] = 1;
printf("%d\n", array_2d[4][0]);
return 0;
}
错误
Allocated 0. column.
Allocated 1. column.
Allocated 2. column.
Allocated 3. column.
Allocated 4. column.
-2002258752 21956 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
Process finished with exit code 139 (interrupted by signal 11: SIGSEGV)
【问题讨论】:
-
int** array_2d; -
array_2d = (int**)malloc(sizeof(int)*size);-->array_2d = (int**)malloc(sizeof(int*)*size); -
因此这也是错误的:
array_2d = (int**)malloc(sizeof(int)*size);.. 这里的元素类型是int *。 -
建议让这个可读性更强,像这样更安全:
array_2d = malloc(size * sizeof(*array_2d))确定拥有正确的类型你的sizeof()总是。
标签: c arrays segmentation-fault