gpt4 book ai didi

使用 malloc 时出现编译器错误(需要左值作为赋值的左操作数)

转载 作者:太空宇宙 更新时间:2023-11-04 06:29:05 25 4
gpt4 key购买 nike

我有 2 个结构,一个指向每个结构的指针和一个指向结构指针的 void **stack

我的问题是在线

(*ptr2+*a)=(struct student *)malloc(sizeof(struct student));

*a 是一个变量,每次发生 stud 注册时都会增加 1,因此我不会一遍又一遍地为同一地址分配内存

因为我在菜单函数然后在输入函数发送了stud(&stud)的地址

*ptr2==stud 

因此

stud[*a]== *(stud+*a)== *(*ptr2+*a)

为什么malloc左边的(*ptr2+*a)错了?部分代码

struct student
{
char flag;
char surname[256];
int semester;
};

main()
{
...
struct student *stud;
menu(stack,stackcopy,reversedstack,&prof,&stud,stacksize,&head);
...
}

void menu(void **stack,void **stackcopy,void **reversed,struct professor **ptr1,struct student **ptr2,int size,int *head)
{
...
input(stack,ptr1,ptr2,size,head,&a,&b);
...
}


int input(void **stack,struct professor **ptr1,struct student **ptr2,int size,int *head,int *a,int *b)
{
...
done=Push(stack,head,(*(int *)ptr2+*a),size);
(*ptr2+*a)=(struct student *)malloc(sizeof(struct student));
stud_input(ptr2,a);
...
}

最佳答案

这是错误的,因为您需要(大致)赋值左侧的变量,而不是值。你不能写1 = 2;,但是你可以写int a; a = 1;。按照同样的逻辑,你不能写&a = (void*)0;

解引用一个指针给你一个变量,所以你可以这样写 struct student *z = &a; *z = b;.

如果你想写stud[*a] = malloc(...);,但是你没有stud,只有ptr2,其中 *ptr2 == stud 成立,显然,正确的方法是,

(*ptr2)[*a] = malloc(...);

(*ptr2)[*a] == *(*ptr2 + *a),所以这也可以工作:

*(*ptr2+*a) = malloc(sizeof(struct student));

关于使用 malloc 时出现编译器错误(需要左值作为赋值的左操作数),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22743923/

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