Trantorian Gazette

Do you know how C pointers work?

Wednesday Jul 20, 2005

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?

Like this post? del.icio.us | furl | slashdot | technorati | digg
Comments:

Post a Comment:
Comments are closed for this entry.