无法获取arg的长度 - C

问题描述 投票:0回答:1

基本上我试图获取参数的长度(使用 strlen),但我不断收到此错误。根据我的理解,这意味着我给出了一个指向 char 数组的指针数组,而不是一个指向 char 数组的指针,但我不明白为什么,因为 argv[i], where 0 < i < argc, should be a "string". Here's the code and the error.

代码:

#include <stdio.h>
#include <string.h>

int main(int argc, char** argv[]){
        if (argc != 2) {
                fprintf(stderr, "INVALID NUMBER OF ARGUMENTS");
                return 1;
        }
        else {
                printf("%d", strlen(argv[1]));
        }
        return 0;
}

错误:

arg.c: In function ‘main’:
arg.c:10:41: warning: passing argument 1 of ‘strlen’ from incompatible pointer type [-Wincompatible-pointer-types]
   10 |                 printf("%d", strlen(argv[1]));
      |                                     ~~~~^~~
      |                                         |
      |                                         char **
In file included from arg.c:2:
/usr/include/string.h:407:35: note: expected ‘const char *’ but argument is of type ‘char **’
  407 | extern size_t strlen (const char *__s)
      |                       ~~~~~~~~~~~~^~~

还尝试将 argv[1] 作为字符串读取(printf("%s", argv[1]);)并且它有效。

c argv strlen
1个回答
0
投票

argv
应声明为
char *argv[]
char **

© www.soinside.com 2019 - 2024. All rights reserved.