C 为什么我的字符串要打印两次?

C 为什么我的字符串要打印两次?,c,C,我想创建一个随机字符串的游戏,用户必须猜测原始字符串是什么,但是当我显示随机字符串时,它会被打印两次。一次随机一次不随机。这是我的密码: #include <stdio.h> #include <stdlib.h> #include <time.h> int checkWin(char guess[], char word[]); void jumble(char array[]); int main() { srand(time(NULL));

我想创建一个随机字符串的游戏,用户必须猜测原始字符串是什么,但是当我显示随机字符串时,它会被打印两次。一次随机一次不随机。这是我的密码:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int checkWin(char guess[], char word[]);
void jumble(char array[]);
int main()
{
    srand(time(NULL));
    char word[5] = {'h', 'e', 'l', 'l', 'o'};
    char scramble[5] = {'h', 'e', 'l', 'l', 'o'};
    char guess[5];
    jumble(scramble);
    printf("The jumled word is: %s\n",scramble);
    printf("Enter a guess: ");
    for(int i = 0; i < 5; i ++)
    {
        scanf(" %c",&guess[i]);
    }
    printf("\n");
    if(checkWin(guess,word))
        printf("You win!");
    else
        printf("You lose");
}
void jumble(char array[])
{
    int a,b,c;
    for(a = 1; a<6; a++)
    {
        b = rand()%5;
        c = rand() %5;
        if(b==c)
        {
            a--;
            continue;
        }
        char temp = array[b];
        array[b] = array[c];
        array[c] = temp;
    }
}
int checkWin(char guess[], char word[])
{
    int a = 0;
    for(int i = 0; i < 5; i ++)
    {
        if(guess[i] == word[i])
            a++;
    }
    if(a==5)
        return 1;
    else
        return 0;
}
我不知道字符串出了什么问题,因此非常感谢您的帮助。

您的字符串不是以NUL结尾的,因此%s格式代码正在两个字符串中运行。如果不需要对齐填充,堆栈变量通常是背靠背排列的,虽然直到它最终在另一个编译器上发现一个巧合的NUL字节时,标准才保证这一点,但它可能会打印出更多的乱码或崩溃

若要修复此问题,请使用隐式添加\0的字符串文字、手动添加\0或将其大小调整为比您初始化的值大一倍。额外的元素隐式为零,例如:

// Not declaring sizes; the arrays size based on the literal to size 6
char word[] = "hello";
char scramble[] = "hello";

您的字符串不是以NUL结尾的,因此%s格式代码正在两个字符串中运行。如果不需要对齐填充,堆栈变量通常是背靠背排列的,尽管在标准最终在另一个编译器上找到一个巧合的NUL字节之前,它决不能保证这一点,它可能会打印出更多的乱七八糟或崩溃

若要修复此问题,请使用隐式添加\0的字符串文字、手动添加\0或将其大小调整为比您初始化的值大一倍。额外的元素隐式为零,例如:

// Not declaring sizes; the arrays size based on the literal to size 6
char word[] = "hello";
char scramble[] = "hello";


谢谢你这解决了我的问题:我接受答案当我能谢谢你这解决了我的问题:我接受答案当我能请写代码认为这是为人类。如果代码只为编译器编写,那么就不需要用英语编写。请在编写代码时考虑到它是为人类编写的。如果代码只为编译器编写,那么就不需要用英语编写。
// Again, autosizing to 6
char word[] = {'h', 'e', 'l', 'l', 'o', '\0'};
char scramble[] = {'h', 'e', 'l', 'l', 'o', '\0'};
// Explicit sizing to 6, implicit initialization of uninitialized element to 0
char word[6] = {'h', 'e', 'l', 'l', 'o'};
char scramble[6] = {'h', 'e', 'l', 'l', 'o'};