Convert int array to string using C

Viewed 3621

So I have something like this:

int array[5] = {1, 6, 2, 4, 4};
char string[255];

/*do something*/

printf("%s\n", string);

Output should be:

[1, 6, 2, 4, 4]

I really don't know where to start...

3 Answers

the following proposed code:

  1. cleanly compiles
  2. performs the desired functionality
  3. demonstrates the use of strcpy() and sprintf()
  4. avoids the use of 'magic' numbers
  5. lets the compiler calculate the number of entries in the array[]

and now, the proposed code:

#include <stdio.h>
#include <string.h>


int main( void )
{
    int array[] = {1, 6, 2, 4, 4};
    char string[255] = {0};

    /*do something*/
    strcpy( string, "[" );
    for( size_t i = 0; i < (sizeof(array)/sizeof(int)) -1; i++ )
    {
        sprintf( &string[ strlen(string) ],  "%d, ", array[i] );
    }

    sprintf( &string[ strlen(string) ],  "%d", array[4] );
    strcat( string, "]" );

    printf("%s\n", string);
}

a run of the proposed code results in:

[1, 6, 2, 4, 4]

You need to convert the integer into equivalent char using the ascii table subtraction and then strcat to the main string

To convert the array to a string, you should use snprintf:

#include <stdio.h>

char *join(char *dest, size_t size, const int *array, size_t count) {
    if (size == 0) {
        return NULL;
    }
    if (size == 1) {
       dest[0] = '\0';
       return dest;
    }
    size_t pos = 0;
    dest[pos++] = '[';
    dest[pos] = '\0';
    for (size_t i = 0; pos < size && i < count; i++) { 
        int len = snprintf(dest + pos, size - pos, "%d%s",
                           array[i], (i + 1 < count) ? ", " : "]");
        if (len < 0)
            return NULL;
        pos += len;
    }
    return dest;
}

int main() {
    int array[5] = { 1, 6, 2, 4, 4 };
    char string[255];

    if (join(string, sizeof string, array, sizeof(array) / sizeof(*array))) {
        printf("%s\n", string);
    }
    return 0;
}
Related