Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/63.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
参数在scanf之后修改_C - Fatal编程技术网

参数在scanf之后修改

参数在scanf之后修改,c,C,我对c非常陌生,我发现在使用scanf函数后,我的char*string参数被修改,c的输入既不会更改最终输出,也不会更改实际参数。虽然看起来代码中接下来的内容确实会改变最终的输出。我在网上找不到这样的例子有人知道这是什么吗?我唯一的想法是我错过了什么,但我看不出是什么 #include <stdio.h> #include <stdlib.h> int method1(char *string){ char c; printf("enter(y/n):

我对c非常陌生,我发现在使用scanf函数后,我的char*string参数被修改,c的输入既不会更改最终输出,也不会更改实际参数。虽然看起来代码中接下来的内容确实会改变最终的输出。我在网上找不到这样的例子有人知道这是什么吗?我唯一的想法是我错过了什么,但我看不出是什么

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

int method1(char *string){
    char c;
    printf("enter(y/n): ");
    scanf("%s", &c);
    printf("%s\n", string);
    return 0;
}

int main() {
    char *string = "string";
    printf("%s\n", string);
    method1(string);
    return 0;
}
#包括
#包括
int method1(字符*字符串){
字符c;
printf(“输入(是/否):”;
scanf(“%s”、&c);
printf(“%s\n”,字符串);
返回0;
}
int main(){
char*string=“string”;
printf(“%s\n”,字符串);
方法1(字符串);
返回0;
}
输出: 一串
输入(是/否):是▒E▒

c
只能保存一个字符。但是

scanf("%s", &c);
将读取多个字符,在
c
中没有空间。因此,这是一个错误。 即使只输入1个字符,
%s
仍需要一个空格来容纳终止的空字节

如果您只想读取单个字符,则可以按如下方式使用:

char c[2];
if (fgets(c, sizeof c, stdin)) {
  /* c[0] contains your input 'y' or 'n' */
}

始终避免
scanf()
。请参阅:

c
只能保存一个字符。但是

scanf("%s", &c);
将读取多个字符,在
c
中没有空间。因此,这是一个错误。 即使只输入1个字符,
%s
仍需要一个空格来容纳终止的空字节

如果您只想读取单个字符,则可以按如下方式使用:

char c[2];
if (fgets(c, sizeof c, stdin)) {
  /* c[0] contains your input 'y' or 'n' */
}
始终避免
scanf()
。见: