gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 08:01:45 24 4
gpt4 key购买 nike

编译器吐出错误说无法将“int 转换为 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();
}

最佳答案

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

#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);
}

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

关于c - 为什么我的指针不能访问结构的成员元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46108613/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com