Thread: Array of integers to string

  1. #1
    Registered User
    Join Date
    Mar 2019
    Posts
    7

    Array of integers to string

    Hello again,

    I have an array of numbers:
    array = [5,6,3]

    I want to make a string from this array in reversed order (I know how to reverse that, but I need to know how to make a string). That string I should use as a return value of a function (so not a print).

    Thank you.

  2. #2
    Registered User
    Join Date
    Feb 2019
    Posts
    1,078
    Here's a trick you may find useful:

    Every printf function (printf, fprintf, sprintf, snprintf, ...) returns the number of chars printed. In particular, snprintf() will return the number of chars that would be "printed" (including the final '\0' of the string), even if the buffer is too short. Example:

    Code:
    char buffer[2];
    
    size = snprintf( buffer, 2, "%d", x ) - 1;
    if x is 2łą-1 (2147483647), size will be 10.

    And, of course, the segund argument (the size of the buffer), includes the final '\0'.

    Knowing this you can write a routine that calculates the total size of the required buffer, allocate it with malloc() and use strcpy/strcat to fill it...

    Good luck.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Array to store integers and string
    By vajra11 in forum C Programming
    Replies: 3
    Last Post: 08-09-2018, 06:59 AM
  2. Replies: 2
    Last Post: 03-02-2014, 05:30 PM
  3. Replies: 2
    Last Post: 03-02-2014, 09:41 AM
  4. Replies: 3
    Last Post: 03-26-2012, 10:50 AM
  5. Extract numbers as integers from a string array
    By DarthC in forum C++ Programming
    Replies: 2
    Last Post: 03-23-2002, 05:09 PM

Tags for this Thread