Can you dynamically allocate a partially fixed-size array in C (2d array)?

92 views Asked by At

I wanted to dynamically allocate a partially fixed size array, but ran into errors which would lead me to believe I don't actually know how an array like this functions, so I'm trying to figure out how would you dynamically allocate in this case? Basically I'm asking how to do what's done in this question, Initialization of 2D array with dynamic number of rows and fixed number of columns. C++ but in pure C.

char *list[256];
int len = 10;
list = (char **) calloc(len, 256);

This is the code I have right now, but I'm getting this error: "error: assignment to expression with array type". Thanks.

2

There are 2 answers

1
Ingo Leonhardt On BEST ANSWER

Maybe you're looking for something like this:

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

typedef char    ROW[256];

int     main( int argc, char *argv[] )
{
        int     nrows = 10;
        ROW     *array = calloc( nrows, sizeof *array );

        // just filling the first columns for demonstration
        for( int row=0; row<nrows; row++ ) {
                for( int col=0; col<5; col++ ) {
                        array[row][col] = row * 10 + col;
                }
        }
        for( int row=0; row<nrows; row++ ) {
                for( int col=0; col<5; col++ ) {
                        printf( "%3d ", array[row][col] );
                }
                fputc( '\n', stdout );
        }
}

Output:

  0   1   2   3   4 
 10  11  12  13  14 
 20  21  22  23  24 
 30  31  32  33  34 
 40  41  42  43  44 
 50  51  52  53  54 
 60  61  62  63  64 
 70  71  72  73  74 
 80  81  82  83  84 
 90  91  92  93  94 

Here, I'm using a typedef to define a a row with a fixed number of columns and use that to create an array with a variable number of rows

5
Federico Turco On

So, do you want to allocate a matrix of size (N, 256)?

You can allocate it as a 2D vector, as:

char **list;
int len = 10;
int i = 0;
list = (char **)malloc(sizeof(char *)*len);
for(i==0; i<len; ++i){
    list[i] = (char *)calloc(256, sizeof(char));
}