为什么&使用scanf后使用的运算符?

时间:2016-08-24 09:19:37

标签: c printf scanf

char string = "default";
printf("The default String is: %s", &string);
scanf("%s", &string);
printf("You entered: %s", &string);

第一个printf语句打印出& string为X(?_?。第二个printf,在scanf语句后打印出我输入的字符串。

由于& var运算符的意思是“var的内存地址”,那么为什么& string打印出输入的字符串?当我尝试使用“string”时,为什么会出现分段错误?

3 个答案:

答案 0 :(得分:3)

您已将string声明为单个字符,但请用字符串填充它。这会调用未定义的行为。您应该将代码更改为:

char string [20] = "default";   //20 is random, you should use the maximum length of the input you may have
printf("The default String is: %19s", string);
scanf("%s", string);
printf("You entered: %s", string);

通常,scanf需要将内存地址作为参数,在上面的代码中,string是内存地址。您可以在this link中详细了解scanf

答案 1 :(得分:1)

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

char chomp(char* s, char c){
    size_t l = strlen(s);
    if (!l) return 0;
    return s[l-1] = s[l-1]==c ? '\0' : s[l-1];
}

int main(){
    char string[] = "default"; /* sizeof(string) == strlen("default")+1 */
    printf("The default String is: %s\n", string); 
    //^ you want the array to decay to a char* here
    /*scanf("%s", &string); -- DANGEROUS 
    -- scanf doesn't know how much space you have in string*/

    fgets(string /*decay again*/,  sizeof(string), stdin);
    /* fgets does know because you've told it with sizeof(string)*/

    chomp(string, '\n');
    printf("You entered: %s", string);
    return 0;
}

答案 2 :(得分:0)

这将是一个解决方案:

char string[20];
strcpy(string, "default");  
printf("The default String is: %s", string);
scanf("%19s", string);
printf("You entered: %s", string);