-1
char a[255];
void test(char* a){
    printf("%d %d %d \n",sizeof(a),sizeof(*a),sizeof(&a));
}

all of those don't get the real size of variable 'a';

Jesper Juhl
  • 30,449
  • 3
  • 47
  • 70
zszen
  • 1,428
  • 1
  • 14
  • 18
  • 1
    You can't, the array decays to a pointer when passed to another function. You can get the size only within the scope of declaration (function-scope in the case of a local array, and file-scope in the case of a global array). – barak manos Jul 06 '16 at 09:05
  • strlen(a); returns the size of the string, but not the whole array – al-eax Jul 06 '16 at 09:06
  • See [How to find the 'sizeof'(a pointer pointing to an array)?](http://stackoverflow.com/questions/492384/how-to-find-the-sizeofa-pointer-pointing-to-an-array). – Lundin Jul 06 '16 at 09:11

3 Answers3

3

You cannot. You will have to pass the size as an additional parameter. Probably of type unsigned int because a size cannot possibly be negative.

void test(char* a, unsigned int size)
{
    // ...
}

Although it's the same end result, it would be even better to make your second argument a size_t, because that's the convention.

void test(char* a, size_t size)
{
    // ...
}
Community
  • 1
  • 1
nvoigt
  • 75,013
  • 26
  • 93
  • 142
3

You should pass it explicitly along with pointer to the first element.

char a[255];
void test(char* a, size_t num_elem){
    /* do smth */
}

int main() {
   test(a, sizeof a / sizeof a[0]);
   return 0;
}

And sizeof a / sizeof a[0] gives you a number of elements inside array, note that this trick won't work properly with pointers but only with arrays.

Sergio
  • 8,099
  • 2
  • 26
  • 52
  • It is worth noting that the `sizeof a / sizeof a[0]` trick works only in `main` function, as `a` is of array type, whereas it doesn't work in `test`, as the global `a` is shadowed by the parameter `a`, that is of a pointer type. – majk Jul 06 '16 at 09:09
  • Yes, that trick should be applied only to arrays, not to the pointers. – Sergio Jul 06 '16 at 09:10
  • 1
    More to the point, it "works" it both places, but once converted to pointer-to-type (such as the case of a parameter), it certainly won't "work" like you want it to. It has been the bane of many-an-engineer in such cases, since *both* cases will compile without error or even warning. – WhozCraig Jul 06 '16 at 09:11
0

You cannot do that. a is of type char*, and that does not have associated size with it. This is why most of the standard library methods to output to a buffer have an extra parameter for specifying the buffer size (see strncpy).

majk
  • 827
  • 5
  • 12