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

Recommended Answers

All 9 Replies

>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'

>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);
}

>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;
}

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...

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.