[英]Program received signal SIGSEGV, Segmentation fault error
Program received signal SIGSEGV, Segmentation fault 程序收到信号SIGSEGV,分段故障
on LINE : if (argv[1][0] == '-'). 在LINE上:if(argv [1] [0] =='-')。
I was trying to make it do something when sees '-c' flag in unix shell 当我在unix shell中看到'-c'标志时,我试图使其执行某些操作
int main(int argc, char **argv)
{
int target_column=1;
int column_flag=0;
int descending_flag=0;
/* command-line argument control */
printf("Argument(s) detected(%d)\n", argc);
/* default mode */
if (argc = 3)
{
if (argv[1][0] == '-')
{
/* column flag */
if (argv[1][1] == 'c')
{
column_flag=1;
printf("column flag found, ");
}
/* error checking */
else
{
fprintf(stderr, "tsort -c <column> [-d]\n");
exit(EXIT_FAILURE);
}
}
Much Appreciate your answers. 非常感谢您的回答。 It was definitely that small typo. 肯定是那个小错字。
If you want to check for the number of the arguments use ==
: 如果要检查参数数量,请使用==
:
if (argc = 3) // This assigns 3 to argc and always yields true
{
if (argv[1][0] == '-')
should be 应该
if (argc == 3)
{
if (argv[1][0] == '-')
Compiler should warn you about this. 编译器应对此发出警告。 If not, always compile with -Wall -Wextra
to avoid this. 如果不是,请始终使用-Wall -Wextra
进行编译以避免这种情况。
You have a typo in your code: 您的代码中有错别字:
if (argc = 3)
should rather be: 应该是:
if (argc == 3)
. 。
People often put the constant on the left to avoid such type of an error, for example: 人们通常将常数放在左侧,以避免此类错误,例如:
if(3 = argc)
would not compile because a constant cannot be assigned to. 将无法编译,因为无法分配常量。
You change the value of argc to 3 on this line: 在此行上将argc的值更改为3:
if (argc = 3)
It should be: 它应该是:
if (argc == 3)
This works (the compiler doesn't give an error message) because assignment has a return value in C++. 这有效(编译器不会给出错误消息),因为赋值在C ++中具有返回值。 In this case that value is 3, which evaluates to true. 在这种情况下,该值为3,其值为true。 Therefore, you will always try to access the first argument looking for '-', which might not exist. 因此,您将始终尝试访问第一个参数,查找“-”,该参数可能不存在。 This leads to a segfault. 这导致段错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.