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...
the following proposed code:
strcpy() and sprintf()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]
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;
}
join return NULL if the snprintf returns negative number, and then in main, test the return and don't call printf? Currently it looks like it might end up calling printf on a string that isn't \0-terminated if that happened, so probably segfault.snprintf is highly unlikely to return -1, except on legacy systems where it could indicate that the output exceeds the available space, which is non-standard conforming. Answer updated.
sprintfto write numbers to a char-buffer and adding the other characters is not that complicated either[1, 6, 2, 5, 5]? If this is the array{1, 6, 2, 4, 4};.'['tostr[0]. Thereafter you need to at least try to write an algorithm of your own. But I can't see anything of that in the question.