我一直在学习字符串,这本书的作者解释了给定的代码我不明白为什么在输出中给11个字符命名,给31个字符短语“表扬”?
输入

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h> /* provides strlen() prototype */
#define PRAISE "You are an extraordinary being."
int main(void)
{
    char name[40];
    printf("What's your name? ");
    scanf("%s", name);
    printf("Hello, %s. %s\n", name, PRAISE);
    printf("Your name of %u letters occupies %u memory cells.\n",
        strlen(name), sizeof name);
    printf("The phrase of praise has %u letters ",
        strlen(PRAISE));
    printf("and occupies %u memory cells.\n", sizeof PRAISE);

    getchar();
    getchar();
    return 0;
}

输出
What's your name? Serendipity Chance
Hello, Serendipity. You are an extraordinary being.
Your name of 11 letters occupies 40 memory cells.
The phrase of praise has 31 letters and occupies 32 memory cells.

据我所知,它应该给出这样的输出
What's your name? Serendipity Chance
Hello, Serendipity. You are an extraordinary being.
Your name of 11 letters occupies 40 memory cells.
The phrase of praise has 3 letters and occupies 32 memory cells.

我哪里弄错了?
对不起,如果这是个愚蠢的问题!!

最佳答案

我认为让您困惑的是scanf("%s", name);只读取第一个空白的数据以你的名义,这就是“意外”,这是11个字符。PRAISE是整个字符串“You are an excessive being.”,它有31个字符长(加上尾随的“\0”)。

08-16 21:49