将参数传递给main [英] passing arguments to main
问题描述
我知道这是很基本的,但是我仍然坚持. 所以我有一个需要带一个变量n的函数,所以这是我的主要功能
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]);
}
我正在这样调用程序:
./sort 4 <text.txt
但是数字4不会被识别或传递给函数.我究竟做错了什么?我知道argv [0]应该包含程序本身的名称,并且每个之后的名称都应该包含参数.
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.
推荐答案
您应尝试全部打印它们.
You should try to print them all.
#include <stdio.h>
int main(int argc, const char *argv[])
{
int i = 0;
for (; i < argc; ++i) {
printf("argv[%d] = '%s'\n", i, argv[i]);
}
return 0;
}
使用./a.out 4 < /somefile
运行该代码会给我:
Running that code with ./a.out 4 < /somefile
gives me:
argv[0] = './a.out'
argv[1] = '4'
最终,您必须记住"4"是指向字符数组的指针,并且可能必须将其解析为整数.
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.
这篇关于将参数传递给main的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!