Thursday, September 30, 2010

Why C Arrays are not really pointers

Ok. This is to settle an argument regarding C, arrays and pointers. I know we were all taught to treat arrays like pointers and they do behave like pointers for the -MOST- part. Try this code for a little mind experiment. Don't cheat! Think about the answer first:


#include <stdio.h>

int main()
{
int len = 100;
char myarr[len];
char *ptr;
ptr = myarr;

printf( "sizeof(myarr) = %d\n", sizeof(myarr) );
printf( "sizeof(ptr) = %d\n", sizeof(ptr) );
return 0;
}


What will this little program print? ;)
Stay tuned for the answer!

Added 24 October 2010:
Oops. I've been so busy I fogot to post a follow up. Anyway, you can easily verify what the answer will be by compiling and running.

No comments: