Mailing List Archive


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [tlug] C puzzle



Viktor Pavlenko wrote:
> 
> I don't think this one satisfies the original request to turn the
> sample into a "correct C program". The original code is much more
> correct than your solution:)

No, my friend. Whether C is "correct" or not is dependent on only one 
thing: compiling and doing what it is supposed to. Macho C hackers 
cackle with glee over this clever use of pointer arithmatic. :)

> Nevertheless it works (despite of gcc complaints). I think it's
> because the pointer to int is unsigned, so negating it results in a
> big positive number.

You would seem to be right:

(gdb) l
1
2       main() {
3         int*i, n=20;
4         for(i = 0 ; i < n ; i--)
5           printf("-");
6       }
(gdb) b 3
Breakpoint 1 at 0x8048466: file test.c, line 3.
(gdb) r
Starting program: /home/jmglov/test

Breakpoint 1, main () at test.c:3
3         int*i, n=20;
(gdb) n
4         for(i = 0 ; i < n ; i--)
(gdb) p i
$1 = (int *) 0x804961c
(gdb) n
5           printf("-");
(gdb) p i
$2 = (int *) 0x0
(gdb) p n
$3 = 20
(gdb) p i < n
$4 = 1
(gdb) n
4         for(i = 0 ; i < n ; i--)
(gdb) p i
$5 = (int *) 0x0
(gdb) n
6       }
(gdb) p i
$6 = (int *) 0xfffffffc
(gdb) p i < n
$7 = 0


-- 
Josh Glover <jmglov@example.com>

Associate Systems Administrator
INCOGEN, Inc.


Home | Main Index | Thread Index

Home Page Mailing List Linux and Japan TLUG Members Links