仅了解C中的列大小来动态初始化2D数组 [英] Initialize 2D array dynamically only knowing its column size in C

查看:43
本文介绍了仅了解C中的列大小来动态初始化2D数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要创建一个包含10列和未指定行数的2D数组.我的想法是 malloc 数组,但是不幸的是,我不知道如何使用2D数组.

I need to create a 2D Array with 10 columns and an unspecified row amount. My idea is to malloc the array but unfortunately I don't know how to do that with a 2D Array.

有人可以给我提供一个简单的代码吗?到目前为止,我有这个:

Can someone provide me with a simple code? So far, I have this:

int arr[][10];
int rows = malloc(sizeof(int));

for (int i = 0; i < 10; i++)
{
    for(int j = 0; j < ???; j++)
    {
        arr[?][i] = 5;
    }
}

很抱歉,但是我是C语言的新手,我正为 malloc free 而苦苦挣扎.

I'm sorry but I'm new to C and I'm struggling with malloc and free.

之后如何以及在哪里释放内存?

How and where do I free the memory after?

我应该放什么而不是? ??? ?

What should I put instead of ? and ????

也许吗?

非常感谢.

推荐答案

如果要分配内存,最终将需要知道所需的数量,没有两种解决方法,但是可以声明一个指向数组的指针固定数量的列,稍后知道行数时,分配所需的空间.

If you want to allocate memory you will eventually need to know the amount you need, there is no two ways about it, you can however declare a pointer to array of a fixed number of columns, and later when you know the number of rows, allocate the space you need.

示例代码并带有注释:

int main()
{
    //pointer to an array with 10 columns
    //at this point the number of rows is not required
    int(*arr)[10];
       
    //to allocate memory you need to know how much of it you need
    //there is no two ways about it, so when you eventually know
    //the number of rows you can allocate memory for it
    arr = malloc(sizeof *arr * 5); // 5 is the number of rows
    
    if(arr == NULL){ //check for allocation errors
        perror("malloc");
        return EXIT_FAILURE;
    }

    for (int i = 0; i < 5; i++)
    {
        for (int j = 0; j < 10; j++)
        {
            arr[i][j] = 5;
        }       
    }
    free(arr); //free the memory when your are done using arr
}


另一种选择是为每个新行在运行时重新分配内存:


Another option is to reallocate memory as you go, for each new row:

实时演示

for (int i = 0; i < 5; i++)
{
    //allocate memory for each new row
    arr = realloc(arr ,sizeof *arr * (i + 1));
    if(arr == NULL){
        perror("malloc");
        return EXIT_FAILURE;
    }
        
    for (int j = 0; j < 10; j++)
    {
        arr[i][j] = 5;
    }       
}


测试打印阵列:


Test printing the array:

for (int i = 0; i < 5; i++) //test print the array
{
    for (int j = 0; j < 10; j++)
    {
        printf("%d", arr[i][j]);
    }   
    putchar('\n');    
}

在两种情况下都会输出:

Will output in both cases:

5555555555
5555555555
5555555555
5555555555
5555555555

这篇关于仅了解C中的列大小来动态初始化2D数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆