Vagish
Vagish

Reputation: 2547

How to get sizeof of array in following case:

I have written a code in C as below,

#define SOB1 10
#define SOB2 20

char Buffer_1[SOB1];
char Buffer_2[SOB2];


char * CommandArray[2] = {Buffer_1,Buffer_2};

How do I get size of Buffer_1 and Buffer_2 indirectly through CommandArray? More precisely I should know value of SOB1 or SOB2 based on the index of char * CommandArray[2]

Upvotes: 3

Views: 97

Answers (3)

Shreemay Panhalkar
Shreemay Panhalkar

Reputation: 196

You can just assign it to the pointer. You need to allocate memory using calloc or malloc.

Upvotes: -2

roelofs
roelofs

Reputation: 2170

You can't do a sizeof in this case, since the array metadata has been lost when you started accessing it via pointer. You would need to use sizeof(Buffer_1) or sizeof(Buffer_2).

Another option (if you don't have access to Buffer_1 and Buffer_2) would be to store a second size variable that is equal to the #define for each Buffer, and use that. Since the array doesn't contain a string, you also can't check for \0 or similar, so you need to be very careful for buffer overruns when using them (another reason to store a size variable).

Upvotes: 4

Bill Lynch
Bill Lynch

Reputation: 81976

Without storing the information yourself, you can't.

Upvotes: 7

Related Questions