我需要编写一个 shell,我的老师要求我们做一个我创建的用户名
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 %s@%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;
}
最佳答案
getpwuid
返回指向 struct passwd
的指针,而不是 char*
。 getlogin
确实返回一个 char*
。但是,如果您在尝试使用 int
初始化 char*
时遇到错误,很可能是因为未声明 getlogin
并且编译器假设它的类型是int
。您是否包含定义这些函数的 header ? getlogin
应包含在
#include <unistd.h>
关于c - 警告 : initialization makes pointer from integer without a cast [enabled by default] char*,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22745870/