Sla*_*ish 2 c malloc memory-management concatenation char
我想连接一段文本,例如"答案是",带有符号整数,给输出"数字是42".
我知道这段文字有多长(14个字符),但我不知道该字符串表示的字符数是多少.
我假设最坏的情况,最大的有符号16位整数有5位数,如果它是负数,还有一个额外的,所以下面的代码是正确的方法吗?
#include <stdio.h>
#include <stdlib.h>
int main()
{
char *message;
message = malloc(14*sizeof(char)+(sizeof(int)*5)+1);
sprintf(message, "The answer is %d", 42);
puts(message);
free(message);
}
Run Code Online (Sandbox Code Playgroud)
使用:
malloc(14*sizeof(char) /*for the 14 char text*/
+(sizeof(char)*5) /*for the magnitude of the max number*/
+1 /* for the sign of the number*/
+1 /* for NULL char*/
);
Run Code Online (Sandbox Code Playgroud)
由于数字将表示为char,因此您必须使用sizeof(char)而不是sizeof(int).