0

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

4
Contributors
9
Replies
10
Views
7 Years
Discussion Span
Last Post by gerard4143
0

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

>Now run it, were you right?
Yup.

0

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 by Dave Sinkula: n/a

0

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

0

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 by gerard4143: n/a

0

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

0

>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

0
#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 by Dave Sinkula: n/a

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.

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.

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

Edited by gerard4143: n/a

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.