1

I've got some to calculate the size of an array. I want to have it dynamically so I don't want to send in the prototype of the function when I call it

I had try some functions, but none of them was good. Here is all functions and variables I had try, with the original array :

unsigned int chnid = 0;
unsigned char aes_key[16] = {0x2B, 0x7E, 0x15, 0x16, 0x28, 0xAE, 0xD2, 0xA6, 0xAB, 0xF7, 0x15, 0x88, 0x09, 0xCF, 0x4F, 0x3C};
unsigned char aes_iv[16] = {0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E,0x0F};

Here is the function prototype :

int init(unsigned int *chnid, unsigned char *aes_key, unsigned char *aes_iv)

And here his call :

s32Ret = init(&chnid, aes_key, aes_iv);

All the test I do :

size_t keyLen = sizeof aes_key;
size_t keyLen2 = strlen((char*)aes_key);
size_t keyLen3 = strlen(reinterpret_cast<char *>(aes_key));

And results :

keyLen = 4
keyLen2 = 20
keyLen3 = 20

Could it be possible that my problem is the size_t type, or I must change the call of my init function?

damadam
  • 330
  • 4
  • 17

1 Answers1

2

Maybe I'm misunderstanding the problem, but are you simply trying to find the size of the array? If so - why not use sizeof?

    unsigned int chnid = 0;
    unsigned char aes_key[16] = { 0x2B, 0x7E, 0x15, 0x16, 0x28, 0xAE, 0xD2, 0xA6, 0xAB, 0xF7, 0x15, 0x88, 0x09, 0xCF, 0x4F, 0x3C };
    unsigned char aes_iv[16] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E,0x0F };
    cout << sizeof aes_key << endl;

Output: 16

Edit: OK, you're passing the array into a function, and querying for the array size inside that function. Well, as noted by other comments here, when inside the question the pointer is just a pointer, so its size is 4. If you want to know the array size, use a container like std::array and then you could use the size method. For passing an std::array to a function see others posts on SO, some of them mentioned in the comments above (e.g. Passing a std::array of unknown size to a function)

Dan
  • 37
  • 8
  • 1
    note that this only works before the array has been passed to the function, inside the function it will have decayed to a pointer – sp2danny May 07 '18 at 10:46
  • Sorry, I *did* misunderstand the question.... I'll edit my response – Dan May 07 '18 at 10:49
  • Reminder: Small letter `o` in `sizeof`; Example Usage: `unsigned char key[54]; printf("size: %i",sizeof(key));` Output: 54 – masarapmabuhay Apr 26 '21 at 08:48