且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

命令参数以argv []相比较是不工作

更新时间:2023-01-29 11:49:36

您无法使用 == 比较字符串。相反,使用 STRCMP

You can't compare strings using ==. Instead, use strcmp.

#include <string.h>

int main (int argc, char * const argv[]) {

if (strcmp(argv[1], "-d") == 0)

// call some function here

}

这样做的理由是,该值...是一个指针重新presenting的第一个字符的位置串中,与之后的字符休息。当您指定 - D在code,它使得在内存中一个全新的字符串。由于新的字符串的位置和的argv [1] 是不一样的, == 将返回 0

The reason for this is that the value of "..." is a pointer representing the location of the first character in the string, with the rest of the characters after it. When you specify "-d" in your code, it makes a whole new string in memory. Since the location of the new string and argv[1] aren't the same, == will return 0.