为char数组分配内存以连接已知的文本和整数

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)

cod*_*ict 7

使用:

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).

  • 我要补充一点,因为`sizeof(char)`是C标准的1,只要'14 + 5 + 1 + 1`就可以了 (3认同)
  • @qrdl:Ya可以工作,但使用sizeof(char)可以清楚地分配什么来保存. (3认同)