Re: Explain why this prints the same
- From: "*** T. Winter" <***.Winter@xxxxxx>
- Date: Thu, 8 Dec 2005 00:56:11 GMT
In article <1133969869.613104.235330@xxxxxxxxxxxxxxxxxxxxxxxxxxxx> "Eric Lilja" <mindcooler@xxxxxxxxx> writes:
> Hello, I'm trying to help someone on a linux-oriented forum. I've taken
> his original code and cleaned it up, but I am still wondering about
> something. Here's the code:
Ok, let's see:
> #include <stdio.h>
>
> int
> main(void)
> {
> int a[][3]={ {1,2,3},{4,5,6,},{7,8,9} };
Well, for a a segment of 9 integers is allocated succesively filled with
the integers 1 to 9.
> int *b = (int *)a;
As 'a' in this context is a pointer to an array of three ints, you are
lying to the compiler. The result is (I think) undefined behaviour.
> int **c = (int **)a;
And more so. Here the result is certain to be undefined behaviour.
> int i = 0;
> int num_elements = sizeof(a) / sizeof(int);
>
> for(i = 0; i< num_elements; ++i)
> printf("*b = %d *c = %d\n", *b++, *c++);
And this is the third time you are lying. You are lucky that
sizeof(int) == sizeof(*int) on your system.
>
> return 0;
> }
....
> The output is:
> *b = 1 *c = 1
....
> *b = 9 *c = 9
>
> Why is it same for *b and *c?
Because on your system sizeof(int) == sizeof(*int) and the compiler
disregards all those lies.
--
*** t. winter, cwi, kruislaan 413, 1098 sj amsterdam, nederland, +31205924131
home: bovenover 215, 1025 jn amsterdam, nederland; http://www.cwi.nl/~***/
.
- Follow-Ups:
- Re: Explain why this prints the same
- From: Old Wolf
- Re: Explain why this prints the same
- References:
- Explain why this prints the same
- From: Eric Lilja
- Explain why this prints the same
- Prev by Date: Re: [OT]How to get my homework done
- Next by Date: Re: Explain why this prints the same
- Previous by thread: Re: Explain why this prints the same
- Next by thread: Re: Explain why this prints the same
- Index(es):