[英]Why does my char array print random trailing characters?
我是編程的新手,我真的需要您的幫助。 在多次調用AddS之后,然后調用ListS以顯示存儲在struct subject * a中的所有內容之后,struct成員標記的第一次打印最多只能正確打印12個字符,然后再打印隨機的尾隨字符。 在循環的下一次迭代中,將使用正確的所有字符打印標記 。 我嘗試減小標簽的大小,似乎它刪除了尾隨的字符。 這里到底發生了什么?
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);
}
realloc()
的第二個參數是新分配的字節大小 。
沒有足夠的代碼顯示可確定的,但是:
tempptr = realloc(a, *subctr + 1);
應該很可能是
tempptr = realloc(a, (*subctr + 1) * sizeof *a);
在結構struct subject
定義的成員char code[7]
小於您在AddS()
函數中定義的char ecode[8]
。
建議您不要使用scanf來讀取輸入,而應該使用fgets和sscanf。 Scanf被認為是相當不安全的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.