c - 程序中打印无效字符

标签 c struct

我已经写好了程序

#include<stdio.h>
struct student
{
    char name[22];
    char rollno[10];
    unsigned long long int phno;

};
int main()
{
    int i,j;
    char c[1];
    struct student cse[10],*p;
    p=cse;
    for(i=0;i<3;i++)
    {
            printf("enter student name\n");
            gets(cse[i].name);
            printf("enter student roll number \n");
            gets(cse[i].rollno);
            printf("enter student phone number \n");
            scanf("%llu",&cse[i].phno);
            gets(c); //to catch the '\n' left unprocessed by scanf
    }
    for(i=0;i<3;i++);
    printf("the following is the information about CSE B student\n");
    printf("%-6s%-24s%-14s%-14s \n","S.no","student Name","Roll no","phone no.");
    for(i=0;i<3;i++)
    {
            printf("%-6d%-24s%-20s%-14llu \n",i+1,(*p).name,(*p).rollno,(*p).phno);
            ++p;
    }
    return 0;
}

输出为

the following is the information about CSE B student
S.no  student Name            Roll no       phone no.      
1     kapil                   1234567890��I      1234567890     
2     kumar                   9876543210��L     9876543210     
3     sharma                  5123467890��a1     5123467980     

Roll no 列中有一些不需要的和无法理解的字符,打印这些无效字符的原因是什么

~

最佳答案

数组rollno只能存储10个字符,但您要输入10个或更多字符。如果您的卷号是 10 位数字,则至少需要 11 个字符才能将其打印为字符串,其中一个额外字符用于终止空字节。从技术上讲,这是 undefined behaviour ,使你的程序无效。

请注意,自 C11 起,gets() 已被弃用,您实际上应该使用 fgets() 来代替。

关于c - 程序中打印无效字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29051410/

相关文章:

c - 相同信息的不同 typedef

c - 有没有办法从 `FILE*` 获取文件名?

c - 编程 Linux 应用程序以同时播放多个声音

c - 读取结构中包含的 char 会导致访问冲突异常

c - 结构的稀疏初始化,任何资源?

iOS/Objective-C - struct objc_class * 和 struct objc_object *

c - 如何在C程序中检查字符串末尾是否有/字符

c - 强制结构成员对齐(使用 IAR 编译器)

c++ - 打开文本文件并读取带有空格的字符串,然后将 2 个单独的整数放入结构中

c - -> 结构体中的运算符