简体   繁体   English

为什么在C中使用printf时字符串会被打印两次?

[英]Why do strings get printed twice when using printf in C?

My program asks the user to provide a string , which will be copied into an array of characters. 我的程序要求用户提供一个字符串 ,该字符串将被复制到一个字符数组中。 Then, with a for loop, the program simply copies the elements of the first array into the second array. 然后,使用for循环,程序只是将第一个数组的元素复制到第二个数组中。

int main() {

    int i;
    char string1[4], string2[4];

    // Get the first string
    printf("Insert your string: ");
    scanf("%s", string1);

    // Copy the values into the second array
    for (i = 0; i < 4; i++) {
        string2[i] = string1[i];
    }

    // Print the second string
    printf("%s", string2);
    return 0;
}

However, when I print the string using the printf() function the string gets printed twice. 然而,当我打印使用字符串 printf()函数的字符串获取打印两次。

Let's say I input the word 假设我输入了这个词

bars 酒吧

The output will be 输出将是

barsbars barsbars

Why is this happening? 为什么会这样?

char string1[4], string2[4];

4-element char array is not enough for 4-character strings. 对于4个字符的字符串,4元素字符数组是不够的。 You need one more for the terminating '\\0' character. 你需要一个终止'\\0'字符。

Why? 为什么?

TL;DR answer: undefined behaviour . TL; DR回答: 未定义的行为

To explain, the problem here, with an input array defined like string1[4] , (4 elements only), an input string like bars will be overruning the allocated memory region (in attempt to store the terminating \\0 ), which in turn invokes undefined behaviour . 为了解释这里的问题,输入数组定义为string1[4] ,(仅限4个元素),像bars的输入字符串将超出分配的内存区域(试图存储终止\\0 ),这反过来又是调用未定义的行为

You should always take care of your input buffer length, like for an input array of string1[4] , your scanf() should look like 你应该总是处理你的输入缓冲区长度,就像string1[4]的输入数组一样,你的scanf()应该看起来像

scanf("%3s", string1);
char bString []= {'s','t','r','i','n','g'};               
printf("bString:%s\n", bString);

Output: 输出:

bString:stringstring bString:stringstring

Solution: Always include the terminating character 解决方案:始终包含终止字符

char bString []= {'s','t','r','i','n','g','\0'};    

Or simply write: 或者简单地写:

char bString [] = "string";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM