Do you know how C pointers work?

Here is a bit of a puzzler. I have a short C program that may not work the way you think it does.

#include 
#include 
int
main(int argc, char **argv) {
int *a=malloc(sizeof(int));
int *b=malloc(sizeof(int));
int *c=malloc(sizeof(int));
*a=6;
*b=2;
*c=*a/*b;
/* can you predict what will print out? */;
printf("*a=%d, *b=%d, *c=%d\n",*a,*b,*c);
}

Try compiling this and see what it does. Did it do what you thought? Do you understand why?

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: