Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array size in multidimensional array with pointers

Tags:

arrays

c

pointers

I'm using a library that creates a multidimensional array in this way:

const unsigned short arrayA[5] = {1, 2, 3, 4, 5};
const unsigned short arrayB[3] = {7, 8, 9};

const unsigned short *multiArray[] ={arrayA, arrayB};

I get the values of it and it works:

printf("03: %d\n", multiArray[0][3]); //4
printf("12: %d\n", multiArray[1][2]); //9

The problem comes when I need to get the size of any of the arrays, I've tried this:

printf("Size of first array: %ld \n", sizeof(multiArray[0])/sizeof(multiArray[0][0]));

It returns 2, probably because it's using addresses.

How can I get the size of the array then?

I have to do this trying not to change the way the arrays are declared, so the arrays are already there and I just need to get the size.

Any approaches?

like image 803
Antonio MG Avatar asked Jun 11 '26 14:06

Antonio MG


2 Answers

It is not possible to deduce the size of the arrays pointed to by the pointers in multiArray since there is no way of performing any computations as the two arrays (arrayA and arrayB) will be stored in arbitrary locations. A good practice is to store the size of the arrays.

like image 111
Ifthikhan Avatar answered Jun 13 '26 08:06

Ifthikhan


You can't. You have to know the size of array in advance and pass it as additional argument.

like image 35
aragaer Avatar answered Jun 13 '26 09:06

aragaer