如何分配二维数组? [重复]

问题描述 投票:0回答:5

我需要创建一个二维数组。目前我将其创建为

int a[100][100]

但是我需要使用C语言中的

malloc
动态分配内存。我用了代码

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

但是现在在将元素输入数组时它显示分段错误。

c arrays multidimensional-array malloc
5个回答
3
投票

您在评论中说

n
是行数。因此,您需要分配
n
行,每行长度为
m
。因此,第二个
for
循环条件应该是
i < n
。另外,您应该检查
malloc
的返回值,以防分配内存失败。我建议进行以下更改 -
NULL

请注意,多维数组并不是一种全新的类型。它只是一个元素数组,其中每个元素本身就是一个数组(对于 2D 数组)、数组的数组(对于 3D 数组)等等。如果您使用
long long **a = malloc(n * sizeof(*a)); for (i = 0; i < n; i++) { a[i] = malloc(m * sizeof(*a[i])); }

,您可以干净简洁地分配数组,如

C99

您还应该了解一下 - 
我如何在 C 中使用动态多维数组?


1
投票
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);

辅助数组,但在输入中您循环了其中的

5

第二个问题是数组索引是

基于零的

,即索引从零开始,直到大小减一。 第三个问题是你扫描了两个数字(为什么?),但你只提供了一个指向

6

的目标指针。

    


0
投票

scanf

如果你想要一大块内存。

如果您想要一个

long *a = malloc(100*100*sizeof(long));

指针数组,然后每个数组位于单独的内存块中,请像这样:


long*

这会创建 1 个 
long **a = malloc(100*sizeof(long*)); for (i=0; i<100; i++) { a[i] = malloc(100*sizeof(long)); }

指针数组,然后创建 1 个每个指针有 100 个

long*
的数组,但我现在不确定你是否说
longs
例如,它是否会计算元素的位置,就像它的位置一样一个连续的块。检查出。 :)
    


0
投票

a[10][15]

否则需要手动计算索引。


0
投票

首先,您需要

#include <stdio.h> #include <stdlib.h> int main(void) { unsigned rows, cols; printf("Enter rows and columns: "); fflush(stdout); scanf("%u%u", &rows, &cols); int (*a)[cols]; // pointer to VLA a = malloc(rows * cols * sizeof a[0][0]); if (a) { for (unsigned r = 0; r < rows; r++) { for (unsigned c = 0; c < cols; c++) { a[r][c] = r*c; } } printf("the element at [4, 2] is %d\n", a[4][2]); free(a); } return 0; }

,但您只为

long long a[100][100]
s
 分配足够的空间

int

您还越界访问数组。索引从 0 开始到 array_length-1。

另一个问题是你扫描了 2 个 int 值,但只提供了 1 的地址。

a[i] = malloc(m * sizeof(int));


您可以分配一个 100 元素的指针数组,每个指针都指向另一个 100 元素数组的数组,但这并不好,因为执行 100
scanf("%d %d",&a[i][j]);

需要时间,并且生成的内存很可能不是连续的,这使得它的缓存不友好。还有一个小的内存开销,因为内存分配器必须将其四舍五入到最接近的块大小,这很可能是 2 的幂,当您在第一维中分配越来越多的元素时,它可能会很大。


您应该声明一个大小为 100*100 的一维数组。这将更快并提高缓存一致性。要获取

malloc

处的元素,只需执行

a[i][j]

a[i*WIDTH + j]

© www.soinside.com 2019 - 2024. All rights reserved.