2013-02-06 70 views
1

我使用通過在主程序中的make_employee函數出返回的指針具有麻煩。分配一個指針到一個結構到可變

//我有一個單獨的.c文件下面的代碼:

struct Employee; 

struct Employee* make_employee(char* name, int birth_year, int start_year){ 
    struct Employee* new = (struct Employee*)malloc(sizeof(struct Employee)); 
    strcpy(new->name, name); 
    new->birth_year = birth_year; 
    new->start_year = start_year; 
    return new; 
} 


//In the main program: 

int main() 
{ 
    char test_name[] = "Fred"; 
    int test_birth = 1989; 
    int test_start = 2007; 

    Employee Fred; 

    make_employee(test_name, test_birth, test_start) = &Fred;  <-- throws invalid lvalue error 

    return 0 
} 
+1

即賦值語句的左側是.... *不*左值。或者在錯誤消息中不清楚。 – WhozCraig

回答

2

不能分配的東西到非左值。因此,名稱(左值,左值可以出現在分配表達式的左側側)。

你想做什麼?

int main() 
{ 
    char test_name[] = "Fred"; 
    int test_birth = 1989; 
    int test_start = 2007; 

    struct Employee *fred = make_employee(test_name, test_birth, test_start) 

    // use fred.... 

    free(fred); 

    return 0 
} 

注意:不要投malloc()在C.確保stdlib.h被包含在源文件中,並讓編譯器警告你,如果你忘了這樣做。如果您收到一個警告,指出大意「的malloc隱式聲明返回int」等,就意味着你忘了,包括stdlib.h,你應該這樣做。

+0

是的,那就是我想要做的。我得到一個警告,在這條線(從初始化兼容的指針類型): 結構僱員弗雷德= make_employee(TEST_NAME,test_birth,test_start); – user2045219

+0

爲您的函數聲明嘗試'struct Employee * make_employee(const char * name,int birth_year,int start_year)'。另外,在相同的源文件中make * sure *它可以是原型或聲明在* main()之上。 – WhozCraig

0

我認爲你需要檢查你的make_employee功能。我之所以這麼說是你公佈你使用以下行

struct Employee* new = (struct Employee*)malloc(sizeof(struct Employee)); 

新是在C++的關鍵字,並應該扔了你的編譯錯誤的時候了,如果你用了一個C++編譯器的代碼。將關鍵字用作變量名是不好的。

也檢查從函數的返回值。

假設您已經聲明瞭結構正確這應該工作以及

struct Employee* make_employee(char* name, int birth_year, int start_year){ 
    struct Employee *ptr = (struct Employee*)malloc(sizeof(struct Employee)); 
    strcpy(ptr->name, name); 
    ptr->birth_year = birth_year; 
    ptr->start_year = start_year; 
    return ptr; 
} 


//In the main program: 

int main() 
{ 
    char test_name[] = "Fred"; 
    int test_birth = 1989; 
    int test_start = 2007; 

    Employee *Fred = make_employee(test_name, test_birth, test_start) ; 

    printf("Printing the data contents"); 
    printf("\n Name : %s",Fred->name); 
    printf("\n Birth : %d",Fred->birth_year); 
    printf("\n Start :%d",Fred->start_year); 
    free(Fred); 
    return 0; 
} 
相關問題