0

I must know array size to which a char pointer variable points.

But you know sizeof operation is not working.

char a[5];
char *b= a;
int c = sizeof(b);
printf("%d", sizeof(b)); // 8(64 bit cpu) printed, not 5 .

Thank you in advance.

inherithandle
  • 2,614
  • 4
  • 31
  • 53

5 Answers5

1

If some piece of code needs to know the size of an array, make sure the code that calls it tells it the size of the array.

David Schwartz
  • 179,497
  • 17
  • 214
  • 278
0

No, once you convert it to a pointer (which is also done when passing the array as an argument to a function) you loose all size information about the array.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
0

Pointers (which is what arrays decay to when you do things like these) don't "know" anything about the size of the data they're pointing at. You need to track it separately.

unwind
  • 391,730
  • 64
  • 469
  • 606
0

you cannot get that information, the only thing you could do is to embeddd the information if it is something you need:

int* array = malloc( sizeof(int) * (n + 1) );
*array = n;
++array;

then when you want to know the size

int n = *(array - 1);

same can be done with char or whatever type you need.

AndersK
  • 35,813
  • 6
  • 60
  • 86
-1

This may be because of of 4 byte alignment.

To confirm try a[8], a[10] etc

hazzelnuttie
  • 1,403
  • 1
  • 12
  • 22
  • 2
    No it's not. It's because `sizeof` yields the size of the object, i.e. the size of the pointer just like it yields the size of the array when an array is the operand. – cnicutar Mar 18 '13 at 12:19