我有一个包含字符串数组的结构,但有时我不知道如何使用它
例如:
struct A
{
char** b;
};
size_t two = 2;
struct A a = malloc(sizeof(struct A));
b = (char**) malloc(sizeof(char*) * 2);
a->b[0] = "1";
snprintf(a->b[1], 4, "%d", two); //this line makes a mess
如果我将 snprintf 用于定义为 char* 类型的变量,则效果非常好,但 a->b[1] 本身不是 char* 类型吗?
为什么它不起作用(如果我在 a->b[1] 上使用 printf,它会显示该值,但当我之后执行任何 malloc 时程序崩溃)以及我应该做什么才能使其工作?
最佳答案
这一行
snprintf(a->b[1], 4, "%d", two);
取消引用a->b[1]
,尚未设置。您无法写入其中。如果您想写入a->b[1]
,请这样做:
a->b[1] = malloc(4);
snprintf(a->b[1], 4, "%3d", two);
现在a->b[1]
有一个4字节的可写内存块。 %3d
将输出限制为三位数字,以防变量 two
设置为更大的数字。
关于c - snprintf 和字符串数组语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36523146/