2014-03-30 34 views
0

我需要編寫一個外殼和我的老師要求我們做的,我通過警告:初始化時將整數指針不進行強制轉換的char [默認啓用] *

char* userName = getlogin(); 

取得用戶名它給我的當我嘗試運行程序時嘗試編譯文件和段錯誤(當我使用eclipse運行它時,它打印NULL)時,在標題中出現警告。

所以,我的問題是char*有什麼錯?爲什麼getlogin給我NULL

這裏是我的代碼是:

int main(void) 
{ 
    char input[INPUT_SIZE+1]; //user's input 
    char hostName[INPUT_SIZE]; 
    //char* userName = getlogin(); 
    char* userName = getpwuid(getuid()); 

    if (gethostname(hostName,255)< 0) { 
     printf("there is no hostname\n", hostName); 
     exit (200); 
    } 
    int code; 
    code=0; 
while(1) 
{ 
    printf("%d %[email protected]%s$ ",code,userName,hostName); 


    fgets(input, INPUT_SIZE, stdin); 
    if(strcmp("\n",input) == 0) 
     continue; 

    printf("it didn't continue\n"); 

    if(strcmp("exit\n",input)==0) 
    { 
     printf("you exit\n"); 
     continue; 
     //exit(127); 
    } 
    printf("it didnt go to exit\n"); 
} 

return EXIT_SUCCESS; 
} 
+1

需要查看getpwuid()定義。你不能從getpwuid中返回一個char *,除非它是堆分配的(在這種情況下你不能釋放)或者它是全局的(這是不尋常的)。很可能,你說錯了。 – avmohan

+1

另外,請確保您獲得您需要的所有原型。使用沒有適當原型的函數太容易出錯。 – Deduplicator

+0

取消註釋'char * userName = getlogin();'並註釋掉下一行,它將起作用。 – jfly

回答

0

getpwuid返回一個指向struct passwd,而不是一個char*getlogin的確返回char*。但是,如果您嘗試使用int嘗試初始化char*時出現錯誤,可能是因爲getlogin未被聲明,編譯器假定其類型爲int。你是否包含了定義這些函數的頭文件? getlogin應包含

#include <unistd.h> 
0

你甚至沒有叫getlogin(),你註釋掉這一行!取消註釋char* userName = getlogin();並註釋掉下一行,它將起作用。

相關問題