【发布时间】:2022-01-01 23:56:29
【问题描述】:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct donor
{
char *name;
char *code ;
char *donor;
char *ship;
char *quant;
char *id;
char *string;
struct donor *link;
} ;
typedef struct donor Donor;
char box[20];
int main(){
Donor *node = malloc(sizeof(Donor));
node-> id = strdup("GA");
node-> code = strdup("HI");
node-> donor = strdup("TO");
node-> ship = strdup("GD");
node-> quant = strdup("UT");
// Combine all nodes' value into box.
sprintf(box, "%s %s %s %s %s", node->id, node->code, node->donor, node->ship, node->quant);
printf("%s", box);
node->string = strdup(box);
printf("%s", node->string);
}
我创建了一个结构体捐助者并为所有节点/变量分配了一个两个字母的字符串。我希望我的 node->string 存储组合的“GA HI TO GD UT”字符串。我在这里尝试 sprintf 将所有节点的值复制到 char 框中,并且 node->string = strdup(box)。但在那之后它不会输出任何东西。有什么想法吗?
【问题讨论】:
-
你告诉
sprintf你想打印多少个字符串,你实际提供了多少个??? -
只有5个,我已经改正了,结果还是一样,没有输出。
-
添加换行符
"%s\n"? -
代码在
-fsanitnize=undefined,address和 Valgrind 下运行良好(尽管有一些漏洞)