为什么我的指针不能访问结构的成员元素

why cant my pointer access the member elements of the structure

编译器吐出错误说无法转换 "int to lin" 并且无法转换 "double to lin" 当我的指针显然指向正确的位置时。

typedef struct lin
{
    int data;
    float next;
}ode;

void main()
{
    ode*head;
    ode a;
    head=&a;
    *head=9;
    head++;
    *head=10.5;
    getch();
}

我认为您对行号感到困惑。您的错误消息中有行号。请咨询他们,并注意下次 整个 错误消息粘贴到 Whosebug 的重要性。

如果您要检查您的错误所抱怨的行(通过行号;查找行号),您会看到:

*head=9;    // an attempt to assign an `int` to a `lin`
*head=10.5; // an attempt to assign a `double` to a `lin`

也许你的意思是:

head->data = 9;
head->next = 10.5

...或...

*head = (struct lin){.data = 9};
*head = (struct lin){.next = 10.5};

很难说。你甚至可以指:

head = &(struct lin){.data = 9};
head = &(struct lin){.next = 10.5};

想想这个。您是否希望您的编译器猜测您要分配给哪个成员?如果有多个 intfloat 成员可供选择怎么办?不提供应该选哪个?

感谢你的编译器 不会 为你猜测,就像你写 head++; 时它会指示你的编译器将指针向前移动一个元素,超出a 结束。这就是所谓的缓冲区溢出。

你在看哪本书?

我想你想给头部的数据赋值,这就是你需要做的 head->data=9; 而不是 *head=9。因为 head 是指向结构 lin 的指针,所以 *head 是 head 的对象,如果你想为对象的数据成员赋值,则使用 object-name -> data-member = value;。同样这里的for浮点数是'head->next=10.5;'。可以参考linkhere and also if you can understand this is another link

如果你只想玩指针,那么你需要以永远不会陷入段错误或类型转换错误的方式进行指针运算。请参考以下代码-

#include <stdio.h>

typedef struct lin
{
    int data;
    float next;
}ode;

void main()
{
    ode*head;
    ode a;
    head=&a;

    *((int*)head)=9; //typecast pointer to int because assigning int value here

    head = (ode*)((char*)head + sizeof(int)); //increase pointer by size of integer as after which memory for float is assigned

    *((float*)head)=10.5;

    head = (ode*)((char*)head - sizeof(int));//go to start of header again

    printf("head->data:<%d>\nhead->next:<%f>",head->data,head->next);
}

由于这在某种程度上会使其他程序员感到困惑且不可读,您可以简单地使用 -> 运算符为结构的数据成员赋值。