-3

I have a problem in displaying the size of the array correctly. I know array size is 256000 but it is displaying as 8 when I enter the loop. size will be displayed accurately if dynamic allocation is not used. How do I rectify the bug using dynamic allocation?

Martin
  • 3,396
  • 5
  • 41
  • 67
Mary
  • 55
  • 4
  • 2
    Are you maybe measuring the size of the pointer pointing to the array? – Enigma Sep 18 '13 at 06:37
  • no. Size of the array – Mary Sep 18 '13 at 06:38
  • 6
    It's pretty damn hard to fix a bug without the code that's causing it. – Chris Hayes Sep 18 '13 at 06:39
  • Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance. – dhein Sep 18 '13 at 06:41
  • possible duplicate of [Sizeof arrays and pointers](http://stackoverflow.com/questions/13672162/sizeof-arrays-and-pointers) – sashoalm Sep 18 '13 at 06:45

1 Answers1

4

This will give you size 10, because the compiler knows it's an array;

char foo[10];
int size = sizeof foo;

This will give you size 4 on a 32-bit architecture, because it's the size of a pointer.

char *foo = malloc(10 * sizeof(char));
int size = sizeof foo;

After this, the usage of foo is identical. You can do foo[2] or *foo or whatever with both versions. But you probably shouldn't take the address of &foo with the 1st variant. And you should free(foo); sometimes with the 2nd.

Always remember: sizeof is not a function, sizeof is always decided in compile time.

SzG
  • 12,333
  • 4
  • 28
  • 41