Mik*_*ohn 2 c malloc command-line-arguments
我从用户那里得到命令行参数.
然后,我为命令切换案例,例如:
case 'f':
*file_name = optarg;
break;
Run Code Online (Sandbox Code Playgroud)
我不确定我是否需要malloc作为指针,因为我不完全理解optarg.
这是file_name的声明方式:
char **file_name;
Run Code Online (Sandbox Code Playgroud)
我应该这样做
int length = strlen(optarg); // This gives a warning about types when compiling.
Run Code Online (Sandbox Code Playgroud)
然后malloc为字符串长度+ 1?
如何针对这类问题完成malloc?请记住,用户输入的文件名为**argv.
编辑:这就是我调用此函数并仍然出现分段错误的方式.
int main(int argc, char **argv)
{
char **file_name;
parser(argc, argvm file_name);
}
void parser(int argc, char **argv, char **file_name)
{
// Switch cases.
}
Run Code Online (Sandbox Code Playgroud)
'optarg'只是指向argv []中元素的指针.因此,不分配内存并复制'optarg'指向的值是安全的.
假设您的程序使用以下参数调用:
myapp -a "hello" -b "world"
Run Code Online (Sandbox Code Playgroud)
你的代码是:
#include <stdio.h>
#include <getopt.h>
void parse_options(int argc, char* argv[], char ** first_arg, char ** second_arg)
{
const char* opt_string = "a:b:";
int opt = -1;
opt = getopt(argc, argv, opt_string);
while (opt != -1) {
switch(opt) {
case 'a':
*first_arg = optarg; /* points to argv[2]="hello" */
break;
case 'b':
*second_arg = optarg; /* points to argv[4]="world" */
break;
default:
break;
}
opt = getopt(argc, argv, opt_string);
}
}
int main(int argc, char* argv[])
{
char* first = 0;
char* second = 0;
parse_options(argc, argv, &first, &second);
printf("first=%s, second=%s\n", first, second);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我的输出:
freebsd% gcc -Wall main.c
freebsd% ./a.out -a hello -b world
first=hello, second=world
Run Code Online (Sandbox Code Playgroud)