c - 变量被 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
我不知道为什么输出字符串被覆盖。任何帮助,将不胜感激
解决方案
问题是,当您使用sprintf将字符串写入字段内容的第一个元素(第一行)时,当字符串长度超过 19 个字符时,您也会写入其第二个元素(第二行)。
您需要增加内容的长度并检查字符串是否合适,或者使用带有额外大小参数的snprintf简单地截断它。
推荐阅读
- html - 使用节点 js 在托管服务器上的 html 文件中自动填充某些参数
- django - Django中的聚合
- python - Platform.system() 给我'str object has no attribute'system'
- javascript - 在点击链接之前,如何将用户返回到他所在页面的上一个位置?
- python - 为什么这段代码不会删除我在 Python 中的反斜杠?
- python-2.7 - 无法更新更改 GPIO 引脚的图像
- c++ - 方法不会覆盖父亲的方法
- javascript - lightbox2 图像库根本不起作用
- firefox - Firefox 扩展:通过 url 显示 iframe
- intellij-idea - 在 IntelliJ 的代码编辑器中,将所选文本用双引号括起来