c - C 中结构的意外行为

标签 c struct scanf turbo-c++

我用 C 编程(使用 Turbo c++)编写了以下代码。

#include<stdio.h>

struct test
{
   char fname[10];
   char age[2];
   char lname[10];
}s1[10];

int main()
{
   int i;
   for(i=0;i<3;i++)
   {
     printf("enter the first name : ");
     scanf("%s",s1[i].fname);
     printf("enter the last name : ");
     scanf("%s",s1[i].lname);
     printf("enter the age : ");
     scanf("%s",s1[i].age);
   }
   for(i=0;i<3;i++)
   {
     printf("\n %s %s age= %s",s1[i].fname,s1[i].lname,s1[i].age);
   }
getch();
return 0;
}

我已经按照要求输入了信息。但是打印结果时发现姓氏(lname)不见了。

你能帮我解决这个意外的结构行为吗? (请忽略值 [10]、声明为字符串的年龄等,因为我出于自己的目的这样做)

请注意:当我将年龄声明为“int”并使用 %d 时,会显示姓氏,但当所有声明为字符时,它不起作用。

最佳答案

char age[2]; 太小了。如果您正好输入 2 个字符,scanf 会将终止字符串写入 lname[0],因为在这种特定情况下,两个数组之间的内存是连续的。

因此 printf 将看到一个空数组,结果将是您观察到的数组

关于c - C 中结构的意外行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21377175/

相关文章:

c - libc stat 函数和 LuaJIT

c - GLFW 按键回调同步

c - 对每个线程都必须可见的变量的单一计算

golang 使用结构本身为 sync.Mutex 和 sync.Cond 初始化成员

c - 如何读取由 scanf 分隔的字符串

c - 对其可包含的元素数量没有预定义限制的数组

c++ - 结构值未输出到屏幕

c - 如何访问 .wav 文件的子 block 数据?

c - 使用 fscanf 读取序列化数据

c - sscanf : skip any number of given chars