在main()内一行中初始化/设置char * argv [] [英] Initialize/set char *argv[] inside main() in one line

查看:112
本文介绍了在main()内一行中初始化/设置char * argv []的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在main()内部初始化/设置char *argv[],以便以后可以在程序中使用argv[1], argv[2]....

I want to initialize/set char *argv[] inside the main() so that I can use argv[1], argv[2]... later in my program.

到目前为止,我知道如何通过两种方式做到这一点:

Up to now, I know how to do this in two ways:

  1. 对于int main(),使用一行作为:

int main()
{
    char *argv[] = {"programName", "para1", "para2", "para3", NULL};
}

请注意,最后使用NULL是因为argv数组中的指针指向根据定义NULL终止的C字符串.

Note that, using NULL in the end is because the pointers in the argv array point to C strings, which are by definition NULL terminated.

对于int main(int argc, char* argv[]),我必须使用多行作为:

For int main(int argc, char* argv[]), I have to use multiple lines as:

int main(int argc,char* argv[])
{
    argv[0] = "programName";
    argv[1] = "para1";
    argv[2] = "para2";
    argv[3] = "para3";
}

我的问题是如何将这两种方法结合在一起,即仅使用一行为int main(int argc, char* argv[])初始化它?特别是,我希望能够做到这一点(目前这是错误的):

My question is that how can I combine these two methods together, i.e. use only one line to initialize it for int main(int argc, char* argv[])? Particularly, I want to be able to do like this (this will be wrong currently):

int main(int argc, char* argv[])
{
    argv = {"programName", "para1", "para2", "para3", NULL};
}

我该怎么做?

编辑:我知道可以在Debugging Command Arguments中设置argv[].我要在main()中进行编辑的原因是,我不想每次都为新的测试用例(不同的argv[]设置)使用Debugging Command Arguments.

Edit: I know argv[] can be set in Debugging Command Arguments. The reason that I want to edit them in main() is that I don't want to bother to use Debugging Command Arguments every time for a new test case (different argv[] setting).

推荐答案

最安全的方法可能是不写到argv引用的内存中(可能不像您想象的那样结构化),而是有另一个大容量:

The safest way is probably don't write into argv referred memory, (that may not be structured as you think), but having another bulk:

int main(int argc, const char** argv)
{
    const char* n_argv[] = { "param0", "param1", "param2" };
    argv = n_argv;
    ...
}

这会将argv从其原始内存(由调用方拥有,并保留在其中)转移到另一个内存中,该内存将在main()的生命期内存在.

This will distract argv from it original memory (owned by the caller, that remains there) to another that will exist for the life of main().

请注意,必须使用const char*来避免使用已弃用的"*分配给char **的字符串"消息.

Note that const char* is required to avoid the deprecated "*string assigned to char**" message.

注意:该代码已在Linux上使用GCC 4.8.1进行了编译,结果如下:

NOTE: this code had been compiled with GCC 4.8.1 on Linux giving the following results:

make all 
Building file: ../main.cpp
Invoking: GCC C++ Compiler
g++ -O0 -g3 -pedantic -Wall -c -std=c++11 -o "main.o" "../main.cpp"
Finished building: ../main.cpp

Building target: e0
Invoking: GCC C++ Linker
g++  -o "e0"  ./main.o   
Finished building target: e0

这篇关于在main()内一行中初始化/设置char * argv []的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆