如何从另一个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 *'
答案 0 :(得分:1)
obj2
的类型为talstrul
,但next
的类型为struct node *
,因此您需要执行
talstrul obj1;
struct node obj2;
obj1.next = &obj2;
因为talstrul
和struct 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.