动态分配2维数组

时间:2013-11-12 03:41:57

标签: c multidimensional-array dynamic-arrays dynamic-allocation

我试图通过动态分配来构建二维数组。我的问题是,它的第一个维度可能需要100个值,那么第二个维度会根据我的问题采用可变数量的值吗?如果有可能那么我将如何访问它?我怎么知道第二维的边界?

4 个答案:

答案 0 :(得分:5)

(参见代码中的评论)

结果你将获得如下所示的数组:

enter image description here

// Create an array that will contain required variables of the required values
// which will help you to make each row of it's own lenght.
arrOfLengthOfRows[NUMBER_OF_ROWS] = {value_1, value_2, ..., value_theLast};

int **array;
array = malloc(N * sizeof(int *));   // `N` is the number of rows, as on the pic.

/*
if(array == NULL) {
    printf("There is not enough memory.\n");
    exit (EXIT_FAILURE);
}
*/

// Here we make each row of it's own, individual length.
for(i = 0; i < N; i++) {
    array[i] = malloc(arrOfLengthOfRows[i] * sizeof(int)); 

/*
if(array[i] == NULL) { 
    printf("There is not enough memory.\n");
    exit (EXIT_FAILURE);        
}
*/
}

答案 1 :(得分:2)

你可以使用100个指针的数组:

int *arr[100];

然后你可以动态地为你想要的任何大小的100个指针中的每一个分配内存,但是你必须记住你已经分配了多少内存(对于每个指针),你不能指望C编译器记住它或告诉它对你而言,sizeof将无法在这里工作。

要访问任何(允许的,在边界内)位置,您只需使用2D数组表示法,例如要访问分配给5th指针的20th内存位置,您可以使用arr[20][5]*(arr[20] + 5)

答案 2 :(得分:1)

我相信OP希望为阵列提供一块内存,并且愿意修复其中一个维度来获取它。我也经常喜欢在用C编码时这样做。

我们以前都曾能做double x[4][];,编译器会知道该怎么做。但有人显然搞砸了 - 甚至可能是有充分理由的。

然而,以下情况仍然有效,并允许我们使用大块内存而不必进行大量指针管理。

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

// double x[4][];

struct foo {
    double y[4];
} * x;

void
main(int ac, char * av[])
{
    double * dp;
    int max_x = 10;
    int i;

    x = calloc(max_x, sizeof(struct foo));
    x[0].y[0] = 0.23;
    x[0].y[1] = 0.45;
    x[9].y[0] = 1.23;
    x[9].y[1] = 1.45;

    dp = x[9].y;
    for (i = 0; i < 4; i++)
        if (dp[i] > 0)
            printf("%f\n", dp[i]);
}

诀窍是在结构中声明固定维度。但请记住,“第一”维度是动态维度,“第二”维度是固定的。这与旧方式相反......

您必须自己跟踪动态维度的大小 - sizeof无法帮助您。

使用匿名的东西,你甚至可以摆脱'y'。

答案 3 :(得分:1)

使用单个指针:

int *arr = (int *)malloc(r * c * sizeof(int));

/ *如何访问数组元素* /

for (i = 0; i <  r; i++)
  for (j = 0; j < c; j++)
     *(arr + i*c + j) = ++count;  //count initialized as, int count=0;

使用指向指针的指针:

int **arr = (int **)malloc(r * sizeof(int *));
for (i=0; i<r; i++)
     arr[i] = (int *)malloc(c * sizeof(int));

在这种情况下,您可以访问与访问静态分配的数组相同的数组元素。

相关问题