[英]C error: lvalue required as unary '&' operand (using pointers)
struct student{
int id;
int score;
};
struct student* allocate(){
/*Allocate memory for ten students*/
struct student *dynamicStudent = malloc(10 * sizeof(struct student));
/*return the pointer*/
return dynamicStudent;
}
int main(){
struct student* stud = NULL;
/*call allocate*/
stud = &allocate();
上面的代碼說“ stud =&allocate();” 是給出左值錯誤的地方。 這是我必須要做的指針分配的一部分,我不知道如何解決此問題。 任何幫助將不勝感激。
您的函數調用不正確。
更改
stud = &allocate();
至
stud = allocate();
struct student* allocate (void)
{
/* Allocate memory for ten students */
struct student *dynamicStudent = malloc(10 * sizeof(struct student));
/* Return the pointer */
return dynamicStudent;
}
由於您的函數allocate (void);
返回struct student
類型的指針,您可以在同類型的stud
收集返回值。
int main (void)
{
/* call allocate */
struct student* stud = allocate(); // <-- Correct Function Call
// …code using stud…
free(stud); // Don't forget to free what you allocate
return 0;
}
&運算符期望一個l值(表示對象的表達式)操作數,其中,當函數返回r值時,將&運算符應用於r值操作數會導致錯誤。 正如您的情況中其他人所指出的那樣,可以通過省略&分配運算符來解決。
分配返回一個指針,因此您不需要使用&。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.