指向对象和C中的指针之间的区别(如何指向另一个指针)

时间:2014-02-13 18:20:55

标签: c pointers struct

如何从另一个struct对象指向struct对象?

这是.h文件:

#include <stdio.h>
#include <stdlib.h>

typedef struct
{
    int num;
    struct node *next;

} talstrul;

这是在.c文件中:

talstrul obj1;
talstrul obj2;

现在我希望obj1的指针指向obj2的指针。所以我试试这个:

obj1.next = &obj2;

但是我收到了一个错误:

'=' : incompatible types - from 'talstrul' to 'node *'

4 个答案:

答案 0 :(得分:1)

obj2的类型为talstrul,但next的类型为struct node *,因此您需要执行

talstrul obj1;
struct node obj2;

obj1.next = &obj2;

因为talstrulstruct node是不同的类型。

答案 1 :(得分:1)

你得到这个错误是因为你试图将obj1的指针指向obj2而不是指向obj2的指针。

如果你想让obj1的指针都指向obj2的指针,那么你必须从node *改为talstrul *,并且可能更容易使用

struct talstrul {
    int num;
    talstrul* next;
};

obj1.next = obj2.next;

obj1.next = &obj2

如果你想让obj1.next实际指向obj2,而不只是指向obj2的指针。

答案 2 :(得分:1)

您需要执行以下操作:

typedef struct talstrul
{
    int num;
    struct talstrul *next;

} talstrul;

talstrul node1;
node1.next = malloc(sizeof (struct talstrul));
talstrul node2;
node1.next = &node2;

答案 3 :(得分:1)

typedef struct
{
    int num;
    struct node *next; //Wrong
} talstrul;

Instead of previous Use this-
typedef struct
{
    int num;
    struct talstrul *next;
} talstrul;
talstrul obj1;
talstrul onj2;
obj1.next = malloc(sizeof(struct talstrul)) //should have the memory right ?
obj1.next = &obj2;

hope this will work. 
相关问题