[英]Why does my char array print random trailing characters?
I'm a complete novice to programming and I really need your help. 我是编程的新手,我真的需要您的帮助。 After calling AddS more than once, and then calling ListS to display everything stored in struct subject *a, the first print of the struct member tag is printed only up to 12 characters correct, followed by random trailing characters.
在多次调用AddS之后,然后调用ListS以显示存储在struct subject * a中的所有内容之后,struct成员标记的第一次打印最多只能正确打印12个字符,然后再打印随机的尾随字符。 On the next iteration of the loop, tag is printed with all characters correct.
在循环的下一次迭代中,将使用正确的所有字符打印标记 。 I've tried lowering the size of tag and it seems that it removed the trailing characters.
我尝试减小标签的大小,似乎它删除了尾随的字符。 What exactly is happening here?
这里到底发生了什么?
struct store
{
char call[7], tag[450];
int units;
};
void AddS(struct store *a, int *n)
{
char ecode[8], etags[450];
int f, error = 0;
struct store *tempptr;
scanf("%s", ecode);
scanf("%d", &f);
scanf("%s", etags);
NameLimit(ecode);
if(Initial(ecode) && Occurrence(ecode, a, *n))
{
printf("Error.\n");
error++;
}
if(!error)
{
if(*n)
{
tempptr = realloc(a, *n + 1);
a = tempptr;
}
if(tempptr || !*n)
{
strcpy((a + *subctr) -> call, ecode);
(a + *n) -> units = f;
if (etags[0] == '.')
(a + *n) -> tag[0] = '\0';
else
strcpy((a + *n) -> tag, etags);
printf("%s added.\n", ecode);
*n = *n + 1;
}
else if(tempptr == NULL)
{
printf("No space.\n");
exit(1);
}
}
}
void ListS(struct store *a, int n)
{
int i, j;
for(i = 0; i < n; i++)
printf("%s %d %s\n", (a + i) -> call, (a + i) -> units, (a + i) -> tag);
}
The second argument to realloc()
is a byte size for the new allocation. realloc()
的第二个参数是新分配的字节大小 。
There's not enough code shown to be sure, but this: 没有足够的代码显示可确定的,但是:
tempptr = realloc(a, *subctr + 1);
should very probably be 应该很可能是
tempptr = realloc(a, (*subctr + 1) * sizeof *a);
在结构struct subject
定义的成员char code[7]
小于您在AddS()
函数中定义的char ecode[8]
。
Instead of using scanf to read input I would recommend you to use fgets and sscanf. 建议您不要使用scanf来读取输入,而应该使用fgets和sscanf。 Scanf is considered to be rather unsafe.
Scanf被认为是相当不安全的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.