将 int 存储在 char* [C] [英] Store an int in a char* [C]
本文介绍了将 int 存储在 char* [C]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
int main()
{
int n = 56;
char buf[10]; //want char* buf instead
sprintf(buf, "%i", n);
printf("%s\n", buf);
return 0;
}
这段代码有效,我的问题是如果我想要相同的行为,buf 是 char* 怎么办?
This piece of code works, my question is what if i want the same behaviour, with buf being a char* ?
推荐答案
buf
是一个静态分配在堆栈上的数组.要使其成为 char *
类型,您需要动态分配内存.我想你想要的是这样的:
buf
is an array statically allocated on the stack. For it to be of type char *
you need to allocate dynamically the memory. I guess what you want is something like this:
int main()
{
int n = 56;
char * buf = NULL;
buf = malloc(10 * sizeof(char));
sprintf(buf, "%i", n);
printf("%s\n", buf);
// don't forget to free the allocated memory
free(buf);
return 0;
}
正如Thomas Padron-McCarthy"在评论中所指出的,您不应该强制转换 malloc()
的返回值.您可以在此处找到更多信息.您也可以完全删除 sizeof(char)
,因为它总是由 1
删除.
As pointed out by 'Thomas Padron-McCarthy' in the comments, you should not cast the return of malloc()
. You will find more info here. You could also remove completely the sizeof(char)
as it will always by 1
.
这篇关于将 int 存储在 char* [C]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文