c - C 语言中字符串的结构空字符(\0) 问题

标签 c string c-strings null-terminated

以下问题是否因空字符而发生。 “是/否”。请解释原因。

第一个代码

#include<stdio.h>  
    struct date{  char day[2];  char month[2];  char year[4];  
    }current_date;

    void main(){
    printf("Enter day: ");     
    scanf("%s",current_date.day);
    printf("Enter month: ");
    scanf("%s",current_date.month);
    printf("Enter year: ");
    scanf("%s",current_date.year);
    printf("\nEntered date is: 
    %s/%s/%s",current_date.day,current_date.month,current_date.year)
    }

输入:
如果我每次扫描时分别输入17,02,1998
输出:

Entered date is: 17021998/021998/1998
当我只是更改结构中的数组长度时,

第二个代码用于相同的输入。

#include<stdio.h>  
    struct date{  char day[3];  char month[3];  char year[5];  
    }current_date;  

其余整个代码是相同的。
输出

Entered date is: 17/02/1998

请解释一下。预先感谢您!

最佳答案

,字符串不是内在类型。 C 字符串约定具有一维字符数组,该数组以空字符('\0')结尾。

使用应该使用的知识

 struct date{  char day[3];  char month[3];  char year[5];  

否则scanf1将无法存储\0 数组,如果您尝试获取 2 位输入(对于 daymonth4 数字年份(使用 %s 格式说明符) - 因为 scanf 会尝试将其写入数组之外,这将是 Undefined Behaviour .

scanf 的用法是

if(scanf("%2s",current_date.day)!=1){
    fprintf(stderr,"Error in input\n");
    exit(EXIT_FAILURE);
}

您定义结构的方式 - 如果您存储相应的值,将为您提供 1 数字月份、1 数字日期和 3 数字年份\0 也。那不是你想要的。在 C 中,字符串是使用 nul 终止的 char 数组实现的 - scanf 存储它们。这就是为什么在我的例子中我使用了 %2s - 这样剩余的空间就可以用来存储 \0

1 这里请注意 reference 中的一件事在 %s 格式说明符

matches a sequence of non-whitespace characters (a string) If width specifier is used, matches up to width or until the first whitespace character, whichever appears first. Always stores a null character in addition to the characters matched (so the argument array must have room for at least width+1 characters).

注意:正如 Simon Berthiaume 在评论中指出的那样 -

You can write string length like this: char year[4+1];, that way it is clear what the content size is intended to be. For example in this case it is 4 digit year that you wanted.

关于c - C 语言中字符串的结构空字符(\0) 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48842085/

相关文章:

c - 如何在 C 中浏览任意长度的字符串数组?

c - fprintf 0 在 Windows MinGW 下给出意想不到的结果

c++ - 如何在 C++ 中使用 std::stoi 将 c 字符串转换为整数

c - 将整数添加到 char 数组以获得良好的输出

c++ - 如何在模板实例化中强制将 char[] 转换为 char*?

c - Pop() 方法总是给出堆栈中的第一个元素而不删除它

c - 如何将主机指针传递到映射设备内存而不复制主机数据?

c++ - 字符串与重复字符的排列(访问数组概念)

c++ - 在LLVM中获取全局字符串值

php - 如何从末尾截断文件名并限制