只有 1 个元素存储的数组超出应有的存储量 [英] Array with only 1 element storing more than it should
问题描述
我的代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct{
char ID[1];
char Content[4];
}
int main(){
DATA z[1];
DATA t;
int c1, c2;
scanf("%c",z[1].ID);
scanf("%s",z[1].Content);
printf("\n");
c1=strlen(z[1].ID);
c2=strlen(z[1].Content);
t=z[1];
printf("t:\n");
printf("%s\n",t.ID);
printf("%s\n",t.Content);
printf("\n");
printf("z:\n");
printf("%s\n",z[1].ID);
printf("%s\n",z[1].Content);
printf("\n");
printf("Length of z's ID: %d.\n",c1);
printf("Length of z's Content: %d.\n",c2);
}
这就是我执行它时得到的:
And this is what I get when executing it:
8
3092
t:
83092
3092
z:
83092
3092
Length of z's ID: 5.
Length of z's Content: 4.
我不知道为什么 ID 应该只有 1 个元素时却有 1 个以上的元素.请帮忙,因为我需要为我正在处理的项目解决这个问题.谢谢.
I don't know why the ID has more than 1 element when it should only have 1. Please help, because I need to fix this for a project I'm working on. Thanks.
推荐答案
我觉得有几个问题.
首先,您在长度为 1 的 z
上使用索引 1.您应该使用索引 0.
First, you use the index 1 on z
which has a length of 1. You should use the index 0.
其次,您使用 %s
打印 ID,它需要一个以空字符结尾的字符数组.您的角色 ID 不是以 null 结尾的,因此它读取的内容比您预期的要多(它会在内容中继续显示).请注意,内容实际上是以空字符结尾的,因为您使用了 %s
而不是 %c
.
Second, you print the ID with %s
which expects a null-terminated character array. Your character ID is not null-terminated and therefore it reads more than you expect (it keeps on going in the Content). Note that Content is in fact null-terminated because you used %s
instead of %c
.
尝试将 printf("%s\n",t.ID);
更改为 printf("%c\n",t.ID);
.
我监督您在长度为 4 的数组中存储 5 个字符(4 个字符和空终止符).正如 @David Bowling 所建议的,您应该使用 %3s
或至少更大尺寸的大批.感谢@David Bowling 指出这一点!
I oversaw that you are storing 5 chars (4 chars and the null-termination) in an array of length 4. As @David Bowling suggests, you should use %3s
or at least a bigger size of your array.
Thanks to @David Bowling for pointing that out!
请注意,我还没有对此进行测试,因为您的示例代码仍然无法正常工作.
Be aware that I have still not tested this, as your example code is still not working.
这篇关于只有 1 个元素存储的数组超出应有的存储量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!