当我在"main"函数中动态分配内存时,程序工作正常。现在我想分配"读取"功能,但每次尝试我都惨败。
我认为我的问题出在我的"主"函数中:我不知道如何从函数"read"中检索结构(指针(,然后通过函数"destroy"释放它动态分配的内存。
int main(void)
{
int err_code;
struct student_t** s=(struct student_t**)malloc(1024*sizeof(struct student_t*));
**s = &read(err_code); //here is: error: lvalue required as unary '&' operand.
//But I think that my problem is wider than just this error.
if (s==NULL) {
puts("Errorn");
}
display(s);
destroy(s);
return err_code;
}
我试图做的是:创建一个结构类型的指针,指向结构的指针,由"read"函数返回。然后将此**指针传递给"销毁"函数,以释放错误定位的内存。
功能。
在函数"读取"中,用户插入分配给结构的数据。返回指向动态分配的结构的指针,如果出现任何错误,则返回 NULL。
struct student_t* read(int *err_code)
{ printf("Insert data:n");
struct student_t* p = (struct student_t *)malloc(1024*sizeof(struct student_t));
*err_code=1;
if (p==NULL) {
puts("Errorn");
return NULL;
}
//then it's supposed to read from user and assing to struct. Code below in links.
}
struct student_t {
char name[20];
char surname[40];
int index;
};
功能释放动态分配的内存,除非"读取"失败并返回 NULL。
void destroy(struct student_t **s)
{
if (s!=NULL) free(s);
}
我的显示功能。但我认为,我的问题开始得更早。
void display(const struct student_t **s) //here I'm unsure if it should be *s- or **s-function.
{
if(s!=NULL) printf("%s %s, %in", (*s)->name, (*s)->surname, (*s)->index);
}
我的"阅读"功能基于我之前问题的答案。当我在"main"中正确分配内存时,它可以工作。我使用的"读取"代码:如何检测用户是否插入带有逗号的数据(以所需的格式(? 其他更简单的"读取",我无法正确处理我想要的所有错误:如何扫描逗号,但逗号未分配给结构?C
我真的很感谢所有的帮助,一切都像是我 150 小时的救赎 为一项任务而苦苦挣扎。
您有两个错误:
你问的那个是因为你做错了。函数返回的值是所谓的r 值。之所以如此命名,是因为它只能位于作业的右侧。它比这稍微复杂一些,但是对于 r 值或l 值(您可以分配给左侧的东西(的常见测试是它的地址是否可以与地址运算符
&
一起获取。R 值不能占用地址。对此的(简单(解决方案很简单:
*s = read(err_code);
第二个错误是因为
read
需要一个指向int
的指针作为其参数,而你传递一个普通的int
变量。在这里,您应该使用地址运算符:*s = read(&err_code);
还有其他一些问题,最大的问题是需要s
成为指向指针的指针。难道不能只是单点,然后简单地做
struct student_t *s = read(&err_code);
另一个问题是,在许多系统中,可能已经存在一个现有的read
函数(最明显的是POSIX系统,如Linux和macOS(,因此您将对该函数有冲突的声明。