OpenCV argc and argv confusion

人走茶凉 提交于 2019-12-11 01:37:20

问题


I'm checking some OpenCV tutorial and found this line at the beginning (here is the link, code is under the CalcHist section http://opencv.willowgarage.com/documentation/c/histograms.html)

if (argc == 2 && (src = cvLoadImage(argv[1], 1)) != 0)

I've never seen this before and really don't understand it. I checked some Q&A regarding this subject but still don't understand it. Could someone explain to me what is the meaning of this line?

Thanks!


回答1:


The line does the following, in order:

  1. Tests if argc == 2 - that is, if there was exactly 1 command line argument (the first "argument" is the executable name)
  2. If so (because if argc is not 2, the short-circuiting && will abort the test without evaluating the right-hand-side), sets src to the result of cvLoadImage called on that command-line argument
  3. Tests whether that result (and hence src) is not zero

argc and argv are the names (almost always) given to the two arguments taken by the main function in C. argc is an integer, and is equal to the number of command-line arguments present when the executable was called. argv is an array of char* (representing an array of NULL-terminated strings), containing the actual values of those command-line arguments. Logically, it contains argc entries.

Note that argc and argv always have the executable's name as the first entry, so the following command invocation:

$> my_program -i input.txt -o output.log

...will put 5 in argc, and argv will contain the five strings my_program, -i, input.txt, -o, output.log.

So your quoted if-test is checking first whether there was exactly 1 command-line argument, apart from the executable name (argc == 2). It then goes on to use that argument (cvLoadImage(argv[1], 1))

Checking argc and then using argv[n] is a common idiom, because it is unsafe to access beyond the end of the argv array.



来源:https://stackoverflow.com/questions/16855386/opencv-argc-and-argv-confusion

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!