Monday 15 August 2011

c - Anything wrong with the code? printed values are not as expected -



c - Anything wrong with the code? printed values are not as expected -

i have above code output not expected.

typedef struct { int a; }node, *nodeptr; nodeptr* createtest() { nodeptr *head = (nodeptr*)malloc(3 * sizeof(nodeptr)); node n1 = { 3 }; node n2 = { 4 }; node n3 = { 5 }; head[0] = &n1; head[1] = &n2; head[2] = &n3; homecoming head; } int main() { nodeptr *n = createtest(); nodeptr n0 = (nodeptr)(n[0]); printf("0: %d\n", n0->a); n0 = n[1]; printf("1: %d\n", n0->a); n0 = n[2]; printf("2: %d\n", n0->a); homecoming 0; }

the output should 3, 4, 5. got 3, 1, , random number. why happens?

head[0] = &n1; head[1] = &n2; head[2] = &n3;

n1, n2, n3 local variables. using address after function createtest exits undefined behavior.

c pointers

No comments:

Post a Comment