printf() 在 C 中的终止字符之后打印一个字符,我该如何解决这个问题?

问题描述 投票:0回答:1

我在 randomString() 中有一个 for 循环,它将随机字符放入字符串的前 x 索引中,其中 x < the string length. I then add a '\0' to the string and print it with printf() but it prints 1 more character than x and that character is always the same, I don't know why.

这是我的代码:

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

#define NELEMS(x) sizeof(x)/sizeof(x[0])
#define MAX_LENGTH 25

void randomChar();
void randomString();

int main()
{
    srand(time(NULL));
    int points = 0;

    randomString(&points, 3);

    return EXIT_SUCCESS;
}

void randomString(int *points, int length)
{    
    char input[MAX_LENGTH], output[MAX_LENGTH];
    do
    {
        int i;
        for (i = 0; i < length && i < NELEMS(output)-1; i++)
            output[i] = (char)(rand() % 26 + 97);
        output[i+1] = '\0';
        //output[i+2] = '\0';

        // for (int i = 0; i < NELEMS(output)-1; i++)
        //     output[i] = i < length ? (char)(rand() % 26 + 97) : '\0';

        
        printf("You have %d points, type %s:\n", *points, output);
        scanf("%s", &input);

        strcmp(input, output) == 0 ? *(points)++ : *(points)--;        
        getchar();
    } while (input[0] != '@');
}

我一直在尝试这个长度为3的函数并得到结果:

You have 0 points, type opc♦:
a
You have 0 points, type lbu♦:
a
You have 14488832 points, type wal♦:
 

使用

output[i+1] = '\0'
output[i+2] = '\0'
不能解决任何问题 注释掉的 for 循环有效,但我不知道为什么第一个循环不起作用

你知道为什么它会打印一个额外的字符吗?

哦,如果你知道为什么 14488832 出现在输出中,我也想知道。

c string c-strings
1个回答
1
投票

这是你的问题:

strcmp(input, output) == 0 ? *(points)++ : *(points)--; 

您正在递增/递减指针

points
,而不是它所指向的内容。结果,你踩到了不应该踩到的记忆,从而触发了未定义的行为

要增加/减少

points
指向的内容,请先将括号移至取消引用。

strcmp(input, output) == 0 ? (*points)++ : (*points)--; 
© www.soinside.com 2019 - 2024. All rights reserved.