Create char array of integer using digits as size

后端 未结 5 426
情歌与酒
情歌与酒 2020-12-19 05:30

I am trying to create a char array in C, to fill it with the digits of an int, but the int can be of any number of digits.

I\'m using a created function called

5条回答
  •  被撕碎了的回忆
    2020-12-19 06:31

    For my money, there is one solution which has gone unmentioned but which is actually simpler than any of the above. There is a combined allocating version of sprintf called "asprintf" available on Linux and most BSD variants. It determines the necessary size, mallocs the memory, and returns the filled string into the first argument.

    char * a;
    asprintf(&a, "%d", 132);
    // use a
    free(a);
    

    Using a stack allocated array certainly removes the need for the free, but this completely obviates the need to ever separately calculate the size.

提交回复
热议问题