Home > Net >  Convert integer array to character array in C
Convert integer array to character array in C

Time:05-24

I need to know how we can convert integer array to character array in C. I have 1000 elements int array and I will have 4000 byte sized char array. How to fill each integer elements into character array so that when printed all integers are shown in single string. Example: dsid_list[3] = {1000, 1001, 1002}; Then char_dsid_array should have "100010011002" Below is the code snippet trying to perform same.

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

int main()
{
        uint32_t dsid_count = 1000;

        printf("dsid_count:%lu\n",dsid_count);

        uint32_t dsid_list[dsid_count];
        uint32_t i;

        printf("start\n");
        for(i=0; i<dsid_count; i  ) {
                dsid_list[i] = i;
        }
        printf("Size of dsid_list:%lu\n", sizeof(dsid_list));

        //char char_dsid_array[sizeof(dsid_list)];
        char *char_dsid_array = (char*)malloc(sizeof(dsid_list)   1);
        
        i=0;
        char* temp = (char*)malloc(4);
        char* temp1 = char_dsid_array;
        for(i=0; i<dsid_count; i  ) {
                sprintf(temp, "%lu", dsid_list[i]);
                if(i == 0) {
                        strcpy(char_dsid_array, temp);
                }
                else {
                        strcat(char_dsid_array, temp);
                }
                char_dsid_array = char_dsid_array   4;
        }
        char_dsid_array = temp1;
        printf("DSID list: %s\n", char_dsid_array);

        free(char_dsid_array);
        free(temp1);
        free(temp);

        return 0;
}

CodePudding user response:

  • Anyway, uint32_t can take values up to 4294967295 (232 - 1), so 4 bytes character space is not enough for storing that number as a string.

  • Luckily, you're trying to create string using numbers in range [0..999]

  • Just loop through the numbers and use return value from sprintf() to suffix numbers to the string. sprintf() (& printf() siblings) returns number of characters written to the target on success.

// after malloc
    int slen = 0;
    for (int num = 0; num < dsid_count;   num)
        slen  = sprintf (char_dsid_array   slen, "%d", num);

    printf("DSID list: %s\n", char_dsid_array);
  • However, if DSIDs are indeed larger than number1000, then you need allocate sufficient space like 10010 (10 x 1001 = 10010) bytes for thousand such IDs to be on the safer side.
  • Once done generating the string, use realloc() to trim unused memory if necessary, like:
char* ptr = realloc (char_dsid_array, slen  1);
if (ptr) char_dsid_array = ptr;
else /* error handling */

CodePudding user response:

4 characters is enough to store the base-10 string representation of integers between 0 and 999, but in general it will no be enough to store an arbitrary int. You can use snprintf to compute the amount of space you need to generate a string representation. I would suggest accumulating the size you will need as you initialize the array and then allocate space once. eg:

#include <assert.h>
#include <stdio.h>
#include <inttypes.h>
#include <string.h>
#include <stdlib.h>
void * xmalloc(size_t s);

int
main(int argc, char **argv)
{
    size_t dsid_count = argc > 1 ? strtol(argv[1], NULL, 10) : 1000;
    size_t needed = 0;
    printf("dsid_count:%zu\n", dsid_count);

    uint32_t *dsid_list = xmalloc(dsid_count * sizeof *dsid_list);
    uint32_t i;

    for( size_t i = 0; i < dsid_count; i = 1 ){
        dsid_list[i] = i;
        needed  = snprintf(NULL, 0, "%" PRIu32, dsid_list[i]);
    }

    char *int_string = xmalloc(needed   1);
    char *end = int_string;
    size_t avail = needed   1;

    for( size_t i = 0; i < dsid_count; i = 1 ){
        int s = snprintf(end, avail, "%" PRIu32, dsid_list[i]);
        end  = s;
        avail -= s;
    }
    assert( end - int_string == needed );
    printf("%s\n", int_string);
}


void *
xmalloc(size_t s)
{
    void *rv = malloc(s);
    if( rv == NULL ){
        perror("malloc");
        exit(EXIT_FAILURE);
    }
    return rv;
}

CodePudding user response:

size_t print(char *buff, size_t size, int *array)
{
    size_t pos = 0;
    int len = 0;

    while(size--)
    {
        len = snprintf(buff   (!!buff) * pos, !!buff * INT_MAX, "%d", *array  );
        if(len < 0) { /* error andling */}
        pos  = len;
    }
    return pos;
}

char *printIntArray(size_t size, int *array)
{
    char *string = malloc(print(NULL, size, array)   1);

    if(string) print(string, size, array);
    return string;
}

int main(void)
{
    int array[3] = {1000, 1001, 1002};
    char *b;
    printf("\"%s\"\n", b = printIntArray(3, array));
    free(b);
}

CodePudding user response:

Sir, down below there is code example for the case:

dsid_list[3] = {1000, 1001, 1002}; Then char_dsid_array should have "100010011002"

Please note some secure issues, before add a new integer to the array we must check there is enough space, before concantenate I will if there is space enough:

if(sizeof(my_list) > (strlen(str_number) strlen(my_list)))

Another cute security recourse is snprintf, this function improves sprintf to avoid overflow.

Here's an online working code link

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

#define INT_CHARS 11 // 5 should be enough, 1000-1999 span 4 digits   '\0', 11 bits are enough for biggest integer number

int main()
{
    int n;
    int length;
    char str_number[INT_CHARS]; // size should enoght to store all digits, null terminator,
    int dsid_list[3] = {1000, 1001, 1002};
    char my_list[4001]= "";

    length = sizeof(dsid_list) / sizeof(int);

    for(n = 0; n < length; n  )
    {
        snprintf(str_number, INT_CHARS, "%d", dsid_list[n]);
        if(sizeof(my_list) > (strlen(str_number)   strlen(my_list)))
        {
            strcat(my_list, str_number);
        }
        else
        {
            printf("Not enough space to store more data\n");
            break;
        }
    }
    printf("my list = %s", my_list);
}
  • Related