为什么我的字符数组打印出随机的尾随字符?

3
我是一个完全的编程新手,真的需要你的帮助。 在调用 AddS 多次之后,并调用 ListS 显示存储在 struct subject *a 中的所有内容后,结构体成员 tag 的第一个打印只打印了前12个字符的正确内容,然后是随机的尾随字符。 在循环的下一次迭代中,tag 会以所有字符的正确形式打印出来。 我已经尝试降低 tag 的大小,似乎它删除了尾随字符。 到底发生了什么?
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);
}   

1
你能同时发布输出吗? - iqstatic
char code[7]; 小于 char ecode[8] - BLUEPIXY
3个回答

3

realloc()函数的第二个参数是新分配内存的字节数。

由于没有展示足够的代码,无法确定,但这段代码可能需要使用realloc()函数来重新分配内存。

tempptr = realloc(a, *subctr + 1);

应该 非常可能

tempptr = realloc(a, (*subctr + 1) * sizeof *a);

问题解决了!非常感谢 @unwind! :-) - user4166213

1
在您定义的结构体 struct subject 中,成员 char code[7] 比您在 AddS() 函数中定义的 char ecode[8] 小。请注意保留 HTML 标签。

-1

不建议使用scanf来读取输入,我建议您使用fgets和sscanf。scanf被认为是相当不安全的。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接