Home > Net >  Easy way declare two dimension array only knowing one element size with malloc?
Easy way declare two dimension array only knowing one element size with malloc?

Time:07-17

How can I declare a two dimensional array only knowing one size of the array. I know the are two collumns but dont know how many rows there are. What's a simple way to declare a CHAR bidemensional array with malloc.

char array[2][?];

CodePudding user response:

Alternatively, if you don't mind that the first index represents the unknown dimension you can declare it as "a pointer to an array of two strings":

char *(*array)[2];

and allocate it in run time as

array = malloc(n * sizeof(*array));

where n is the variable holding the actual size of the array.

Then you can use it as an ordinary array. For example:

array[n-1][0] = "foo";
array[n-1][1] = "bar";

CodePudding user response:

Using the pointer array, such as

char* a[2];

Then assign the address of one dimensional array to it.

char b[2] = { 'a', 'b' };
a[0] = b;
// or dynamic assign
a[1] = (char*)malloc(sizeof(char)*4);

And you get a two dimensional array whit diffenent size (2 and 4) in each dimension. you can simply access one element using eg. a[0][1] ( which refers 'b').

  •  Tags:  
  • c
  • Related