为什么在执行命令行参数解析时,`optarg`变量始终未被新的值覆盖?

2026-04-16 19:093阅读0评论SEO资源
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计325个文字,预计阅读时间需要2分钟。

为什么在执行命令行参数解析时,`optarg`变量始终未被新的值覆盖?

我是getopt(3)的新手,看了些例子,遇到了这个问题。这些行case 'c': cvalue=optarg; break;看起来很奇怪,因为optarg的内容不会复制到cvalue中,它只是复制了指针。但奇怪的是,它竟然有效:$testopt -a -b -c fooaf

我是getopt(3)的新手,看了一些例子,遇到了 this one.

这些线

case 'c': cvalue = optarg; break;

看起来很怪异,因为optarg的内容不会被复制到cvalue中,它们只是复制指针.但它有效:

$testopt -a -b -c foo aflag = 1, bflag = 1, cvalue = foo

我希望通过第二次调用getopt()来覆盖optarg,所以我根据这个例子编写了我的own program.令人惊讶的是,optarg不会被覆盖.

$testopt -p -f me -t you pflag = 1, from = me, to = you

这是否一致,还是应该总是复制/复制?
我是否必须照顾optarg中返回的所有内容?
我真的很幸运,optarg的realloc()不会分配到同一个地址吗?

从 GNU manuals开始:

为什么在执行命令行参数解析时,`optarg`变量始终未被新的值覆盖?

If the option has an argument, getopt returns the argument by storing it in the variable optarg. You don’t ordinarily need to copy the optarg string, since it is a pointer into the original argv array, not into a static area that might be overwritten.

这就是为什么它不需要复制或分配. POSIX documentation需要这个optarg.

本文共计325个文字,预计阅读时间需要2分钟。

为什么在执行命令行参数解析时,`optarg`变量始终未被新的值覆盖?

我是getopt(3)的新手,看了些例子,遇到了这个问题。这些行case 'c': cvalue=optarg; break;看起来很奇怪,因为optarg的内容不会复制到cvalue中,它只是复制了指针。但奇怪的是,它竟然有效:$testopt -a -b -c fooaf

我是getopt(3)的新手,看了一些例子,遇到了 this one.

这些线

case 'c': cvalue = optarg; break;

看起来很怪异,因为optarg的内容不会被复制到cvalue中,它们只是复制指针.但它有效:

$testopt -a -b -c foo aflag = 1, bflag = 1, cvalue = foo

我希望通过第二次调用getopt()来覆盖optarg,所以我根据这个例子编写了我的own program.令人惊讶的是,optarg不会被覆盖.

$testopt -p -f me -t you pflag = 1, from = me, to = you

这是否一致,还是应该总是复制/复制?
我是否必须照顾optarg中返回的所有内容?
我真的很幸运,optarg的realloc()不会分配到同一个地址吗?

从 GNU manuals开始:

为什么在执行命令行参数解析时,`optarg`变量始终未被新的值覆盖?

If the option has an argument, getopt returns the argument by storing it in the variable optarg. You don’t ordinarily need to copy the optarg string, since it is a pointer into the original argv array, not into a static area that might be overwritten.

这就是为什么它不需要复制或分配. POSIX documentation需要这个optarg.