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