4

我从来没有理解过这个错误,而且我一直遇到类似的错误,这真的很令人沮丧,因为我找不到解决方案。(如果还有其他的请不要抨击我,因为我找不到它)。

看一段简单的代码:

#include <stdio.h>
#include <stdlib.h>

int main(int argc,char *argv[]){
    char s[10];
    int x = strtol(argv[1], &s, 10);
    printf("%d", x);
    printf("%s", s);
    return 0;
}

我不断收到这些错误,但我真的不明白为什么:

警告:从不兼容的指针类型 [-Wincompatible-pointer-types] int x = strtol(argv[1], &s, 10) 传递“strtol”的参数 2;

注意:预期为 'char ** restrict' 但参数类型为 'char (*)[10]'</p>

当我更改char s[10]char *s使用 strtol 的行时,我收到一个段错误。我不明白出了什么问题,有人可以解释一下吗?提前致谢。

4

3 回答 3

4

更改char s[10]char *s是解决编译错误的正确方法。 strtol的第二个参数应该是指向指针变量的指针,它将初始化为指向作为其第一个参数的字符串中的 某个位置。char s[10]不声明指针变量,char *s确实如此。

我能想到的唯一解释,为什么这个程序可能会崩溃,是你没有给它传递任何参数。在那种情况下argc将小于 2 并且argv[1]将是一个空指针(或者甚至可能没有初始化)。你需要做这样的事情:

#include <stdio.h>
#include <stdlib.h>

int main(int argc,char *argv[])
{
    if (argc != 2) {
        fprintf(stderr, "usage: %s integer\n", argv[0]);
        return 1;
    }

    char *s;
    long x = strtol(argv[1], &s, 10);
    printf("x: %ld\n", x);
    printf("s: '%s'\n", s);
    return 0;
}

顺便说一句,在 C 中,出于历史原因,首选样式是将函数定义的左大括号放在自己的行上,即使所有其他左大括号都被“拥抱”。

于 2019-07-25T19:26:53.753 回答
2

&s 是指数组的地址。它实际上是一个指向指针的指针。您想要的是传入数组名称 s,它是指向数组 s 的第一个字符的指针。

#include <stdio.h>
#include <stdlib.h>

int main(int argc,char *argv[]){
    char s[10];
    int x = strtol(argv[1], s, 10);
    printf("%d", x);
    printf("%s", s);
    return 0;
}
于 2020-02-01T11:32:10.580 回答
0

您需要创建一个变量,char *然后将其传递给函数。不可能以这种方式传递数组,因为它不会衰减到char **.

#include <stdio.h>
#include <stdlib.h>

int main(int argc,char *argv[]){
    char s[10];
    char* s_ptr; //New variable, char *

    int x = strtol(argv[1], &s_ptr, 10);
    printf("%d", x);
    printf("%s", s_ptr);
    return 0;
}

strtol请参阅函数 文档: http ://www.cplusplus.com/reference/cstdlib/strtol/

于 2019-07-25T19:11:53.380 回答