C语言 动态分配的二维数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19920452/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 07:57:05  来源:igfitidea点击:

Dynamically allocated 2 dimensional array

cmultidimensional-arraydynamic-arraysdynamic-allocation

提问by tryu hjkl

I am trying to build two dimensional array by dynamically allocating. My question is that is it possible that its first dimension would take 100 values, then second dimension would take variable amount of values depending on my problem? If it is possible then how I would access it? How would I know the second dimension's boundary?

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

回答by yulian

(See the comments in the code)

(见代码中的注释)

As a result you'll get an array such like the following:

因此,您将获得如下所示的数组:

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);        
}
*/
}

回答by Don't You Worry Child

You can use array of 100 pointers:

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

int *arr[100];

int *arr[100];

then you can dynamically allocate memory to each of the 100 pointers separately of any size you want, however you have to remember how much memory (for each pointer) you have allocated, you cannot expect C compiler to remember it or tell it to you, i.e. sizeofwill not work here.

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

To access any (allowed, within boundary) location you can simply use 2D array notation e.g. to access 5thlocation of memory allocated to 20thpointer you can use arr[20][5]or *(arr[20] + 5).

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

回答by duanev

I believe the OP wants a single chunk of memory for the array, and is willing to fix one of the dimensions to get it. I frequently like to do this when coding in C as well.

我相信 OP 需要为数组分配一块内存,并且愿意修复其中一个维度来获得它。在用 C 编码时,我也经常喜欢这样做。

We all used to be able to do double x[4][];and the compiler would know what to do. But someone has apparently messed that up - maybe even for a good reason.

我们过去都能够做到double x[4][];,而编译器会知道该做什么。但显然有人把它搞砸了——甚至可能是有充分理由的。

The following however still works and allows us to use large chunks of memory instead of having to do a lot of pointer management.

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

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

The trick is to declare the fixed dimension in a struct. But keep in mind that the "first" dimension is the dynamic dimension and the "second" one is fixed. And this is the opposite of the old way ...

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

You will have to track the size of your dynamic dimension on your own - sizeof can't help you with that.

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

Using anonymous thingies you might even be able to git rid of 'y'.

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

回答by Aashish

Using a single pointer:

使用单个指针:

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

/* how to access array elements */

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

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

Using pointer to a pointer:

使用指向指针的指针:

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

In this case you can access array elements same as you access statically allocated array.

在这种情况下,您可以像访问静态分配的数组一样访问数组元素。