convert int to char* in standard C (without itoa)

拜拜、爱过 提交于 2019-12-13 15:05:55

问题


I have declared and initialized two variables as shown below:

int a=5;
char* str;
str = (char*)calloc(255, sizeof(char));

I want to convert the int to char* in standard C. I cannot use any conversion function from C++ such itoa.

I am using Ubuntu 11.10


回答1:


First of all, itoa is not a C++ thing.

You can simply use sprintf:

sprintf(str, "%d", a)

In a real application you'll want to use snprintf though to remove the risk of a buffer overflow:

str = malloc(16);
snprintf(str, 16, "%d", a);

And 15 characters are way enough to store an integer.



来源:https://stackoverflow.com/questions/8770408/convert-int-to-char-in-standard-c-without-itoa

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!