加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 为什么`optarg`没有被覆盖?

发布时间:2020-12-16 09:21:35 所属栏目:百科 来源:网络整理
导读:我是getopt(3)的新手,看了一些例子,遇到了 this one. 这些线 case 'c': cvalue = optarg; break; 看起来很怪异,因为optarg的内容不会被复制到cvalue中,它们只是复制指针.但它有效: $testopt -a -b -c fooaflag = 1,bflag = 1,cvalue = foo 我希望通过第二次
我是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开始:

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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读