【发布时间】:2013-11-27 08:00:03
【问题描述】:
我有一个结构,其中存储了一些值,如下所示:
struct cmd {
char *pname;
char *pdesc;
};
在初始化之后我做了:
struct cmd[] = {{"show", "show items"},
{"exit", "exit the shell"},
{"setitem", "setting item"}
};
我正在使用sprinf() 通过存储所有 pname 和 pdesc 来打印,如下所示,
int length = 0;
char *resultcmd;
for (indx = 0; indx< cmdCount; indx++) {
length += sprintf(resultcmd+length, cmd[indx].pname, cmd[indx].pdesc);
}
请帮助我如何为 resultcmd 分配内存,当我将 resulecmd 设置为一定长度的数组时,它起作用了,但是如果添加更多 pname 和 pdesc 缓冲区溢出。请帮帮我。
【问题讨论】:
-
使用 strlen 计算字符串长度。
-
你能提前算出所需的总内存吗?
-
如果使用
glibc并且不关心对其他libc 实现的可移植性,会说坚持使用gcc,您可能想看看asprinf()。
标签: c malloc printf dynamic-memory-allocation