C 预期‘;字符**限制和#x2019;但参数的类型为‘;字符(*)[x]’;
我从来没有理解过这个错误,我经常遇到类似的错误,这真的很令人沮丧,因为我找不到解决方法。(如果还有一个,请不要责怪我,因为我找不到它) 看一段简单的代码:C 预期‘;字符**限制和#x2019;但参数的类型为‘;字符(*)[x]’;,c,C,我从来没有理解过这个错误,我经常遇到类似的错误,这真的很令人沮丧,因为我找不到解决方法。(如果还有一个,请不要责怪我,因为我找不到它) 看一段简单的代码: #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); print
#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;
}
#包括
#包括
int main(int argc,char*argv[]){
chars[10];
intx=strtol(argv[1],&s,10);
printf(“%d”,x);
printf(“%s”,s);
返回0;
}
我不断收到这些错误,但我真的不明白为什么:
警告:从不兼容的指针类型[-Wincompatible指针类型]传递'strtol'的参数2
intx=strtol(argv[1],&s,10)
及
注意:应为“char**restrict”,但参数的类型为“char(*)[10]”
当我将
char s[10]
更改为char*s
时,我在使用strtol的线路上收到一个segfault。我不明白出了什么问题,有人能解释一下吗?提前感谢。您需要创建一个变量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;
}
#包括
#包括
int main(int argc,char*argv[]){
chars[10];
char*s_ptr;//新变量char*
int x=strtol(argv[1],&s_ptr,10);
printf(“%d”,x);
printf(“%s”,s_ptr);
返回0;
}
请参阅strtol功能的文档:
将
chars[10]
更改为char*s
是解决编译错误的正确方法strtol
的第二个参数应该是指向指针变量的指针,它将初始化该指针变量以指向作为其第一个参数的字符串中的某个位置chars[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;
}
#包括
#包括
int main(int argc,char*argv[])
{
如果(argc!=2){
fprintf(stderr,“用法:%s整数\n”,argv[0]);
返回1;
}
char*s;
长x=strtol(argv[1],&s,10);
printf(“x:%ld\n”,x);
printf(“s:'%s'\n',s);
返回0;
}
顺便说一句,在C语言中,出于历史原因,首选的样式是将函数定义的大括号放在它自己的行中,即使所有其他大括号都是“拥抱”的。&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;
}
#包括
#包括
int main(int argc,char*argv[]){
chars[10];
int x=strtol(argv[1],s,10);
printf(“%d”,x);
printf(“%s”,s);
返回0;
}
Hmm,这似乎仍然会导致segfault。因此,是时候在发生故障的地方进行调试了。它发生在strtol
函数中,不是因为s_ptr
指针。