[英]expected 'char * restrict' but argument is of type 'char' ,char * __cdecl strcpy(char * __restrict__ _Dest,const char * __restrict__ _Source); in C
[英]expected ‘char ** restrict’ but argument is of type ‘char (*)[x]’
我從來沒有理解過這個錯誤,我一直遇到類似的錯誤,這真的很令人沮喪,因為我找不到解決辦法。 (如果還有另一個請不要抨擊我,因為我找不到它)。
看一段簡單的代碼:
#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 ** 限制' 但參數的類型為 'char (*)[10]'
當我將char s[10]
更改為char *s
我在使用 strtol 的行上收到段錯誤。 我不明白出了什么問題,有人可以解釋一下嗎? 提前致謝。
將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 中,由於歷史原因,首選樣式是將函數定義的左花括號放在自己的行上,即使所有其他左花括號都是“擁抱”的。
&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;
}
您需要創建一個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 : strtol
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.