One day while pondering about C I came up with this program. Can you predict what the answer will be? Now run it, were you right?


filename.c

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char**argv)
{
	unsigned long *iptr = (unsigned long*)0;/*pointer equals 0*/
	unsigned long ans = (unsigned long)(iptr + 1);/*add 1 to the pointer*/
	
	fprintf(stdout, "and the answer is->%lu\n", ans);/*whats the answer?*/
	exit(EXIT_SUCCESS);
}

gcc filename.c -Wall -ansi -pedantic -o filename

>Can you predict what the answer will be?
I can certainly try.

>Now run it, were you right?
Yup.

PC-lint for C/C++ (NT) Vers. 8.00u, Copyright Gimpel Software 1985-2006
main.c:7: Warning 413: Likely use of null pointer 'iptr' in left argument to operator 'ptr+int'

Edited 6 Years Ago by Dave Sinkula: n/a

>Can you predict what the answer will be?
I can certainly try.

>Now run it, were you right?
Yup.

Yeah, its was intended for the rookies not the seasoned vets..

PC-lint for C/C++ (NT) Vers. 8.00u, Copyright Gimpel Software 1985-2006
main.c:7: Warning 413: Likely use of null pointer 'iptr' in left argument to operator 'ptr+int'

If that warning is a problem then try:

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char**argv)
{
	unsigned long *iptr = (unsigned long*)1;/*pointer equals 1*/
	unsigned long ans = (unsigned long)(iptr + 1);/*add 1 to the pointer*/
	
	fprintf(stdout, "and the answer is->%lu\n", ans);/*whats the answer?*/
	exit(EXIT_SUCCESS);
}

Edited 6 Years Ago by gerard4143: n/a

>Yeah, its was intended for the rookies not the seasoned vets..
Good thing I didn't give away the answer then. ;)

>Yeah, its was intended for the rookies not the seasoned vets..
Good thing I didn't give away the answer then. ;)

Yeah you were a good sport about that..Thanks

#include <stdio.h>
#include <stddef.h>

int main(void)
{
   ptrdiff_t diff;
   unsigned long ans, *iptr = &ans;
   printf("iptr = %p\n", (void*)iptr);

   ++iptr;
   printf("iptr = %p\n", (void*)iptr);

   diff = iptr - &ans;
   printf("diff = %d\n", diff);

   return 0;
}

Edited 6 Years Ago by Dave Sinkula: n/a

I could also come up with the correct answer before I ran the program, but it certainly caught my brain for a few minutes.

I could also come up with the correct answer before I ran the program, but it certainly caught my brain for a few minutes.

Yeah when you take something like this program which is out of context...it well looks weird...

Edited 6 Years Ago by gerard4143: n/a

This article has been dead for over six months. Start a new discussion instead.