【发布时间】:2015-12-04 18:09:31
【问题描述】:
持续接受三个数字并打印三个数字中的最大值的程序。 我收到运行时错误(SIGABRT) 这是我的代码
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
char ch[30];
char *c[3];
long int i[3], mx_2;
int o;
while((fgets(ch,sizeof(ch),stdin))&&ch!='\0')
{
c[0] = (char *)malloc(10);
c[1] = (char *)malloc(10);
c[2] = (char *)malloc(10);
c[0] = strtok(ch," ");
c[1] = strtok(NULL," ");
c[2] = strtok(NULL," ");
i[0] = atoi(c[0]);
i[1] = atoi(c[1]);
i[2] = atoi(c[2]);
mx_2 = i[0] > i[1] ? (i[0] >i[2] ? i[0] : i[2]) : (i[1] > i[2] ? i[1] : i[2]);
printf("%ld\n",mx_2);
fflush(stdin);
for (o = 0; o < 3; o++) {
free(c[o]);
}
}
return 0;
}
任何帮助家伙 谢谢
【问题讨论】:
-
在
c[0]=strtok(ch," ");之后立即执行i[0]=atoi(c[0]);并检查c[0] != NULL。类似i[1]=atoi(c[1]); i[2]=atoi(c[2]); -
请注意
ch!='\0'始终为假,因为您将ch的地址与'\0'进行比较。 -
free(c[o]);这个点不能释放它,因为malloc的返回值被strtok的返回值重写(不需要malloc和free。) -
一如既往:请不要在 C 中强制转换
malloc& co 的返回值(在 C++ 中必须这样做,但在 C 中这被认为是不好的做法)
标签: c if-statement dynamic conditional