gpt4 book ai didi

c - 是什么导致此代码中的段错误?

转载 作者:太空宇宙 更新时间:2023-11-04 08:36:11 25 4
gpt4 key购买 nike

我目前正在类里面学习 Linux 终端命令的 C 实现,但我似乎无法在我的机器上运行以下示例。我正在使用最新的 Ubuntu 发行版。它会编译但有警告。 “赋值从没有强制转换的整数生成指针”它指的是带有 a=ctime(&n->ut_time) 的行;我在网上找到了这段代码。假设复制终端命令“Who”以显示系统用户。我只是想研究它是如何工作的,但我似乎无法让它运行。任何帮助或解释将不胜感激。

#include<stdio.h>
#include<sys/utsname.h>
#include<utmp.h>
int main(void)
{
struct utmp *n;
char *a;
int i;
setutent();
n=getutent();
while(n!=NULL)
{
if(n->ut_type==7)
{
printf("%-9s",n->ut_user);
printf("%-12s",n->ut_line);
a=ctime(&n->ut_time);
printf(" ");
for(i=4;i<16;i++)
{
printf("%c",a[i]);
}
printf(" (");
printf("%s",n->ut_host);
printf(")\n");
}
n=getutent();
}
}

最佳答案

正在转移评论以回答

编译器告诉你你没有 #include <time.h>所以ctime()假定返回 int而不是 char * .由于您没有注意编译器警告,一切都乱套了(段错误等)。

请记住,在您学习 C 时,编译器对 C 的了解比您多得多。应该注意它的警告。 (当你相当了解 C 时,你仍然会注意编译器警告 - 并使代码在没有警告的情况下干净地编译。我使用 gcc -Wall -Wextra -Werror 和一些额外的选项——通常是 -Wmissing-prototypes -Wstrict-prototypes -Wold-style-definition -Wold-style-declaration ;有时是 -Wshadow-pedantic ;偶尔还有其他一些。)

关于c - 是什么导致此代码中的段错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26152329/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com