structures with pointers.find the output

Aug 29, 2012 at 5:47pm
#include<conio.h>
#include<stdio.h>

void main() {
struct st {
int i;
struct st *j;
}t1,t2;
clrscr();
t1.i=123;
t2.i=456;
t1.j=&t2;
t2.j=&t1;
printf("%d\n%d",*t2.j,*t1.j);
}


checked it with compiler
*t2.j=123
*t1.j=garbage value;
can anybody explain me why ?
Aug 29, 2012 at 6:02pm
What do you get after correcting the errors?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <stdio.h>

int main()  {
    struct st   {
        int i;
        struct st *j;
    }t1,t2;

    t1.i=123;
    t2.i=456;

    t1.j=&t2;
    t2.j=&t1;

    printf("%d\n%d\n", t2.j->i, t1.j->i);
}

I get 123 and 456, as you probably intended: http://ideone.com/JOFlQ

The errors were wrong return type of main, which wouldn't affect the output, and wrong arguments to printf, which results in undefined behavior.

PS: If your system is anything like this GCC/linux I tested on, printf() expects to see integer arguments in certain CPU registers: ESI for the first %d, EDX for the second %d. You're passing structs, which are stored on stack instead, and the registers contain whatever intermediate values they happen to have at this point of execution.

Last edited on Aug 29, 2012 at 6:15pm
Aug 29, 2012 at 8:37pm
Oh I see the difference now.

Trying to call a pointer with " . " instead of " -> "

http://www.cplusplus.com/reference/std/new/operator%20new/
Topic archived. No new replies allowed.