Initialize 2D array dynamically only knowing its column size in C [closed]

耗尽温柔 提交于 2021-02-17 07:05:20

问题


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

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 ????

row maybe?

Thanks a lot.


回答1:


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.

Sample code with comments:

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:

Live demo

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



回答2:


Maybe a typedef will help you?

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

void seqr(void *d, int n) {
    int *a = d;
    for (int k = 0; k < n; k++) a[k] = k;
}

typedef int row10[10]; // helper typedef

int main(void) {
    int n = 42;
    row10 *rows = malloc(n * sizeof *rows);
    if (rows) {
        seqr(rows, n * 10);
        printf("%d, %d\n", rows[0][0], rows[n - 1][9]);
        free(rows);
    }
    return 0;
}


来源:https://stackoverflow.com/questions/63505685/initialize-2d-array-dynamically-only-knowing-its-column-size-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!