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

标签 c memory-management malloc char concatenation

我想连接一段文本,例如“答案为”和带符号整数,以给出输出“数字为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);
}

最佳答案

用:

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*/
      );

由于数字将被表示
作为字符,您必须使用sizeof(char)
而不是sizeof(int)。

关于c - 为char数组分配内存以连接已知的文本和整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2334131/

相关文章:

c++ - 为什么 C++17 引入 std::aligned_alloc?

c - 为什么在同一地址空间的两个不同指针上调用 malloc?

c - 是否有必要对 malloc 和 calloc 进行类型转换

C - 我在编写 "rotate right"函数时遇到问题

c - OpenGL 中的位图渲染方法?

c++ - 类似函数的宏参数名称替换保证永远不会发生吗?

c++ - '=' 标记之前预期的构造函数、析构函数或类型转换”

c++ - 为什么实例化后什么也没有发生? (C++ 内存分配器实现)

c - Malloc 和 free 错误

c++ - 比较 float 的正确方法