我需要创建一个二维数组。目前我将其创建为int a[100][100]
但我需要使用动态分配内存malloc
在C语言中。我用了代码
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int n=6, m=5, i, j;
int **a = malloc(n * sizeof(int *));
for(i = 0; i < m; i++)
a[i] = malloc(m * sizeof(int));
for( i = 1; i <= n; i++ )
{
for( j = 1; j <= m; j++ )
{
scanf("%d %d",&a[i][j]);
}
}
return 0;
}
但现在在将元素输入数组时它显示分段错误。
你在评论中说n
是行数。所以你需要分配n
每行长度m
。因此,第二个for
循环条件应该是i < n
。另外,您应该检查返回值malloc
for NULL
万一分配内存失败。我建议进行以下更改 -
long long **a = malloc(n * sizeof(*a));
for (i = 0; i < n; i++) {
a[i] = malloc(m * sizeof(*a[i]));
}
请注意,多维数组并不是一种全新的类型。它只是一个元素数组,其中每个元素本身就是一个数组(对于 2D 数组)、数组的数组(对于 3D 数组)等等。如果您正在使用C99
,您可以干净简洁地分配数组,如下所示
int nrow = 4; // number of rows
int ncol = 8; // number of columns
// define arr to be a pointer to an array of ncol ints, i.e.,
// arr is a pointer to an object of type (int[ncol])
int (*arr)[ncol] = malloc(sizeof(int[nrow][ncol]));
// check the result of malloc for NULL
if (arr == NULL) {
printf("malloc failed to allocate memory\n");
// handle it
}
// do stuff with arr
for (int i = 0; i < nrow; i++) {
for (int j = 0; j < ncol; j++) {
arr[i][j] = i + j;
}
}
// after you are done with arr
free(arr);
你还应该经历这个 -如何在 C 中使用动态多维数组? https://stackoverflow.com/q/917783/1809377
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)