You are here:

C/Malloc in C

Advertisement


Question
Hi,

I wrote the following testing code:

int main()
{
   char *a;
   a = malloc(20);
   printf("%d
", sizeof(1)); // prints 4
   a[0] = 1;
   printf("%d
", sizeof(a)); //prints 1

}

why will sizeof(a), sizeof(*a) and sizeof(a[0]) be 1? If I store 4 int into a, do I access the last int by a[3]? If yes then why is the sizeof(a[x]) 1 instead of 4? If each element in a is 1 byte, then how do I access the last int I stored? Thank you.

Answer
Hello Pearson.

Any integer number, like 1, is by default, four bytes long. So sizeof(1) prints 4 because 1 is an integer.

char* pa means that pa is a pointer to a character data type. Any pointer (on a 32 bit operating system) is 4 bytes long so sizeof(pa) is 4.

If you have char* pa, and you de-reference pa using *pa or pa[0], then you are accessing the value that pa points to. In this case, that value is of type char, and char is 1 byte long, so sizeof(*pa) is 1 and sizeof(pa[0]) is 1 too.

You can cast pa as an integer and store an integer into the memory like this:
*((int*)pa) = 123;
Then you can access individual bytes of pa with pa[0], pa[1], etc. The last byte will be at pa[3].

Of course, you must malloc at least 4 bytes to store an integer into the memory pointed at by pa. If you allocate less, the results are unpredictable, but generally will be bad.

I hope that helps you out.

Best regards
Zlatko

C

All Answers


Answers by Expert:


Ask Experts

Volunteer


Zlatko

Expertise

No longer taking questions.

Experience

No longer taking questions.

Education/Credentials
No longer taking questions.

©2012 About.com, a part of The New York Times Company. All rights reserved.