【问题标题】:Assigning optarg to an int in C将 optarg 分配给 C 中的 int
【发布时间】:2013-05-16 04:00:10
【问题描述】:

我正在尝试将 optarg 值分配给 int,但编译器给了我以下警告:

warning: assignment makes integer from pointer without a cast [enabled by default]

我已经尝试在分配之前将 optarg 强制转换为 int

n = (int) optarg;

但仍然收到警告:

warning: cast from pointer to integer of different size [-Wpointer-to-int-cast]

我不确定需要做什么才能简单地将 optarg 分配给一个整数,然后打印它(现在)。

int main (int argc, char *argv[])
{
  char c;
  int n;

  while ((c = getopt(argc, argv, "m:")) != -1) {
    switch (c) {
    case 'm':
      n = optarg;
      break;
    }
  }

  printf("%d\n", n);

  return 0;
}

【问题讨论】:

  • 这是 64 位 Linux 吗?如果是这样,将 int 更改为 long
  • @Mellowcandle:不一定。或许作者知道n是一个很小的整数……
  • 对初学者特别有用的提示:使用gcc -Wall -g 编译并改进您的程序,直到没有给出警告。然后学习如何使用gdb 调试器。

标签: c unix casting int


【解决方案1】:

选项字符串总是一个字符串。

如果你想要一个整数,你需要使用一个转换函数,比如atoi(3)

所以你至少应该编码

n = atoi(optarg);

注意,optarg 可能是 NULL,当然也可能是非数字。您可以使用strtol(3),它可以设置您要检查的结束字符。

所以更严肃的方法可能是

case 'm':
  {
     char* endp = NULL;
     long l = -1;
     if (!optarg ||  ((l=strtol(optarg, 0, &endp)),(endp && *endp)))
       { fprintf(stderr, "invalid m option %s - expecting a number\n", 
                 optarg?optarg:"");
         exit(EXIT_FAILURE);
       };
      // you could add more checks on l here...
      n = (int) l;
     break;
  }
  n = optarg;
  break;

注意l 作为表达式的赋值以及if 测试中的comma operator

顺便说一句,GNU Libc 也有argp 函数(还有getopt_long - 但argp 函数更强大),你可能会觉得更方便。一些框架(特别是 Gtk 和 Qt)也具有程序参数传递功能。

如果你正在做一个严肃的程序,请让它接受--help 选项,如果可能的话,接受--version 选项。真的很方便,我讨厌少数不接受它们的程序。看看GNU standards 怎么说。

【讨论】:

  • 我的手册页说 strtol 接受一个基数作为最后一个参数。这可能意味着代码段有错误? long int strtol(const char *nptr, char **endptr, int base);
【解决方案2】:

optarg 是一个指向字符串的指针——如果你想将它转换为整数,最简单的方法是使用atoi

case 'm':
    n = atoi(optarg);
    break;

【讨论】:

    猜你喜欢
    • 2016-07-04
    • 2021-12-14
    • 2018-02-03
    • 1970-01-01
    • 2013-10-15
    • 2011-09-03
    • 2022-01-04
    • 2020-07-23
    相关资源
    最近更新 更多