开发者

How to make a C program pointer point to itself

I have a C program and I have to modify it so that a links to itself, b links to开发者_如何学Go c and c links to b.

It does compile. But I'm not sure if I did it correctly.

#include <stdio.h>

int main(){
  struct list {
    int data;
    struct list *n;
  } a,b,c;

  a.data=1;
  b.data=2;
  c.data=3;
  b.n=c.n=NULL;
  a.n=a.n=NULL;
  a.n= &c;
  c.n= &b;

  printf(" %p\n", &(c.data)); 
  printf("%p\n",&(c.n));
  printf("%d\n",(*(c.n)).data);
  printf("%d\n", b.data);
  printf("integer %d is stored at memory address %p \n",a.data,&(a.data) );
  printf("the structure a is stored at memory address %p \n",&a );
  printf("pointer %p is stored at memory address %p \n",a.n,&(a.n) );
  printf("integer %i is stored at memory address %p \n",c.data,&(c.data) );
  getchar();
  return 0;
}

How do I have a pointer link to itself?


You say:

a links to itself, b links to c and c links to b

Then in your code you write this:

b.n=c.n=NULL;
a.n=a.n=NULL;

Let's go step by step:

b.n=c.n=NULL;

Break it down in:

c.n=NULL;
b.n=c.n;

Instead of assigning c to b and b to c you're assigning NULL to c.n and then the value of c.n (NULL, since you just did so) to b.c.

My C is a little weak but you probably wants something like this:

b.n = &c;
c.n = &b;

This uses & the address-of operator. The same works for the a.n=a.n=NULL; expression.


b.n=c.n=NULL;
a.n=a.n=NULL;

b and c link to nowhere; a links to nowhere (twice)

a.n= &c;
c.n= &b;

a links to c; c links to b

You wanted a linking to a; b linking to c, and c linking to b ... so ... FAIL :-)


Given:

list *a, *b, *c;
a=(list *)malloc(sizeof (list));
b=(list *)malloc(sizeof (list));
c=(list *)malloc(sizeof (list));
  • a links to itself

    a->n=a;
    
  • b links to c

    b->n=c;
    
  • c links to b

    c->n=b;
    

Can you see what you did wrong?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜