"Kenneth Brody" <kenbrody@spamcop.netwrote in message
news:43971F85.8FD77233@spamcop.net
pemo wrote:
>>
>"Eric Lilja" <mindcooler@gmail.comwrote in message
>news:1133969869.613104.235330@
>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:
>>
>#include <stdio.h>
>>
>int
>main(void)
>{
>int a[][3]={ {1,2,3},{4,5,6,},{7,8,9} };
>int *b = (int *)a;
>int **c = (int **)a;
>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++);
>>
>return 0;
>}
>>
>When compiled I get:
>gcc -Wall -W -ansi -pedantic -g -c -o pointer_wonder.o
>pointer_wonder.c
>pointer_wonder.c: In function `main':
>pointer_wonder.c:13: warning: int format, pointer arg (arg 3)
>
Note the warning here. ("*c++" is an "int*" type.)
>
>gcc pointer_wonder.o -o pointer_wonder.exe
>>
>The output is:
>*b = 1 *c = 1
[]
>*b = 9 *c = 9
>>
>Why is it same for *b and *c?
>>
>*b gives you back an int
>>
>whereas
>>
>*c gives you back an int *
>>
>However, the 'values' of each are taken from a.
>
And it happens to be that sizeof(int)==sizeof(int*). Try it on a
system where this is not true, such as an old 16-bit DS compiler
in large model mode. (sizeof int == 2, and sizeof int* is 4.)
In a test here, I get:
*b = 1 *c = 1
*b = 2 *c = 3
*b = 3 *c = 5
*b = 4 *c = 7
*b = 5 *c = 9
*b = 6 *c = 2013
*b = 7 *c = 2013
*b = 8 *c = 9
*b = 9 *c = 2680
>
>So, printf would really like a %p (at least) for the third arg.
>
Though it would still print (basically) the same thing, as *c is
still really an int being treated as int*.
--
In any case, this probably falls under the "UB" heading, as you are
taking int's and treating them as int*'s.
(Yes, I know the apostrophes don't really belong in the last sentence,
but it makes it more legible, IMH)
That's so cool!
I really should *invest* in an 'old' compiler! And, it'd be so great to
have a 'Take me Back' experience of my own [in an archive.org kinda sense].
Like, if only I'd saved some of programs I 'cut' into 7-hole punched tape (I
never had access to the punched cards!: they were [for eyes only] in the
domain of the machine room ops!)
I used to have my first Ph.D. thesis on one of those removable hard drives -
big clunky things, with equaly big handles!
, I'm 48 - anyone care to beat that?
Fart