Reputation: 20410
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?
Upvotes: 2
Views: 4586
Reputation: 21
It is possible to obtain both the amount of rows and columns of a matrix:
int main(void) {
int row;
int column;
int matrix[4][5]={{1,2,3,4,5},{1,2,3,4,5},{1,2,3,4,5},{1,2,3,4,5}};
row=sizeof(matrix)/sizeof(matrix[0]);
column=sizeof(matrix[0])/row;
printf("row %i \n",row);
printf("column %i \n",column);
return 0;
}
Upvotes: 2
Reputation: 41046
As other have said, you can not, instead you can build your own type:
#include <stdio.h>
struct cont {
const unsigned short *value;
size_t len;
};
int main(void)
{
const unsigned short arrayA[5] = {1, 2, 3, 4, 5};
const unsigned short arrayB[3] = {7, 8, 9};
struct cont arrays[] = {
{arrayA, sizeof(arrayA) / sizeof(arrayA[0])},
{arrayB, sizeof(arrayB) / sizeof(arrayB[0])},
};
printf("03: %d\n", arrays[0].value[3]);
printf("12: %d\n", arrays[1].value[2]);
printf("Size of first array: %ld \n", arrays[0].len);
return 0;
}
Upvotes: 1
Reputation: 19463
You cant! you should hold this data and pass it to wherever you need.
BTW when you do this: sizeof(multiArray[0])/sizeof(multiArray[0][0])
you basically do sizeof(<pointer>)/sizeof(<unsigned short>)
=> 2 on your specific machine.
Upvotes: 1
Reputation: 1474
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.
Upvotes: 4
Reputation: 409442
If you do sizeof
on a pointer, you get the size of the actual pointer and not what it points to. You have to keep track of the size of the contained array some other way.
Upvotes: 2
Reputation: 17858
You can't. You have to know the size of array in advance and pass it as additional argument.
Upvotes: 2