Hello everyone,
I am trying to build a function that takes a struct that contains an array of integers, which I know the length (size) of, and convert it to a nicely formatted character array (string) output in C.
I am trying to do a nicely printed output in my function like this:
[]
[3]
[3, 4]
[3, 4, 6]
My code is:
I have a problem though because sometimes the int array has number bigger than 0-9. I tried using itoa() but it does not seem to solve my problem because it adds a null terminated character at the end. I also have problem finding how much memory I can to allocate as I don't know how big the integers will be.Code:typedef struct { /* A pointer to a dynamically allocated array to hold the elements. */ int *element; /* The length of the array. */ int length; /* The capacity as a list. */ int capacity; } IntArray; char *toString(IntArray *ar) { /* * Returns a string to be printed, from an IntArray. */ char *str; // Check for empty array if (ar->length == 0) { str = (char *) malloc(3 * sizeof(char)); if (str == NULL) { printf("*** Memory request failed. ***\n"); exit(EXIT_FAILURE); } str[0] = '['; str[1] = ']'; str[2] = '\0'; } // Otherwise: else { int i = 0, j = 0; int size = ar->length * 3 + 3; str = (char *) malloc(size * sizeof(char)); str[j] = '['; while (i != ar->length) { str[++j] = '0' + ar->element[i++]; str[++j] = ','; str[++j] = ' '; } str[--j] = ']'; str[++j] = '\0'; } return str; }
It works great for an int array of 0's, but when I have different numbers this function does not work anymore.
I will really appreciate your help as I have been stuck on this function for quite a bit.
Thank you very much.