将参数传递给 main
我知道这是相当基本的,但我仍然被困住。 所以我有一个函数需要接受变量 n,所以这是我的主函数
int main(int argc, char* argv){
sort(argv[1]);
}
我像这样调用程序:
./sort 4 <text.txt
但是数字 4 没有被识别或传递到函数中。我做错了什么?我知道 argv[0] 应该保存程序本身的名称,并且从那里开始的每个程序都应该保存参数。
I know this is fairly basic, but I'm still stuck.
So I have a function that needs to take in a variable n, so this is my main function
int main(int argc, char* argv){
sort(argv[1]);
}
And I'm calling the program like this:
./sort 4 <text.txt
But the number 4 doesnt get recognized or passed into the function. What am I doing wrong? I know that argv[0] should hold the name of program itself and each one from there on should hold the arguments.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您应该尝试将它们全部打印出来。
使用
./a.out 4 < 运行该代码/somefile
给我:最终你必须记住“4”是一个指向字符数组的指针,你可能必须将它解析为一个整数。
You should try to print them all.
Running that code with
./a.out 4 < /somefile
gives me:Eventually you'll have to remember that the '4' is a pointer to an array of characters, and you might have to parse it into an integer.
char *argv
不正确。您将获得一个char*
数组(“字符串”),因此声明main
的正确方法是int main(int argc, char *argv[ ])
或等效的int main(int argc, char **argv)
(在后一种情况下,数组参数有效地转换为指向数组第一个元素的指针)。您在当前版本的代码中检索的是由环境重新解释为字符数组的环境提供的参数指针数组中的第二个
char
,这完全是另一回事。char *argv
is not correct. You get passed an array ofchar*
("Strings"), so the correct way to declaremain
would beint main(int argc, char *argv[])
or equivalentlyint main(int argc, char **argv)
(in the latter case the array-argument is effectively converted to a pointer to the first element of the array).What you are retrieving in the current version of the code is the second
char
in the array of argument-pointers given to you by the environment reinterpreted as an array of characters, which is something else entirely.正如其他人所描述的,您知道如何获取所有参数,但不知道“
这不是您的程序的参数,而是 shell 的参数。这是输入重定向,意味着文件的输入将传入程序,就像来自 stdin(键盘)一样。
为了防止这种情况,只需像这样调用您的程序:
我不确定您正在调用的函数“sort”是什么。
As described by other you know how to get all argument, but not the "<text.txt".
This is not an argument to your program, but to the shell. This is input redirection, meaning that the input of the file is coming to the program as if it come from stdin (the keyboard).
To prevent this, just call you program like this:
I am not sure what the function "sort" is, that you are calling.