首页 > 解决方案 > 变量被 printf 中的后续变量覆盖

问题描述

我没有得到变量的完整单词,它被下一个元素覆盖 代码是这样的。

#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h>
struct item
{
    struct data
    {
        char content[10][20];
    } details;
    struct item *next;
};
typedef struct item product;
void display(struct data *variable)
{
    int i = 0;
    struct data *v = variable;
    while (strcmp(v->content[i], "END") != 0)
    {
        printf("Element : %s \n", v->content[i]);
        i++;
    }
}
struct data *init_Tshirt()
{
    char usage_type[20];
    struct data *new_data = (struct data *)malloc(sizeof(struct data));
    printf("Enter The Usage type(Sports_Usage/Casuals_Usage): ");
    scanf("%s", usage_type);
    sprintf(new_data->content[0], "Usage Type = %s", usage_type);
    strcpy(new_data->content[1], "END"); // used as a deliminator
    return new_data;
}
struct data *init_Saree()
{
    char material_type[20];
    struct data *new_data = (struct data *)malloc(sizeof(struct data));
    printf("Enter The Material(Cotton_Material/Silk_Material): ");
    scanf("%s", material_type);  
    sprintf(new_data->content[0], "Material Type = %s", material_type);
    strcpy(new_data->content[1], "END"); // used as a deliminator
    return new_data;
}
int main()
{
    struct data *variable1 = init_Tshirt();
    display(variable1);
    struct data *variable2 = init_Saree();
    display(variable2);
}

输出是

Enter The Usage type(Sports_Usage/Casuals_Usage): Sports_Usage
Element : Usage Type = Sports_END
Enter The Material(Cotton_Material/Silk_Material): Cotton_Material       
Element : Material Type = CottEND

我希望输出是

Enter The Usage type(Sports_Usage/Casuals_Usage): Sports_Usage
Element : Usage Type = Sports_Usage
Enter The Material(Cotton_Material/Silk_Material): Cotton_Material       
Element : Material Type = Cotton_Material

我不知道为什么输出字符串被覆盖。任何帮助,将不胜感激

标签: cloopsvariablesoutputprintf

解决方案


问题是,当您使用sprintf将字符串写入字段内容的第一个元素(第一行)时,当字符串长度超过 19 个字符时,您也会写入其第二个元素(第二行)。

在此处输入图像描述

您需要增加内容的长度并检查字符串是否合适,或者使用带有额外大小参数的snprintf简单地截断它。

https://pubs.opengroup.org/onlinepubs/9699919799/


推荐阅读