Question

I'm attempting to convert an array of ints to an array of strings in c. My code so far is:

int args[] = {1, 3000};
char *str_args[15];
int i = 0;
for(i; i<=((sizeof(args)/sizeof(args[0]))); i++){
       char buffer[10];
       sprintf(buffer, "%d", args[i]);
       str_args[i] = buffer;
}
printf("%s\n", *str_args[0]);

This code causes my program to crash instead of outputting 1 (the first arg) like I expect. What am I missing here? Thanks in advance

Was it helpful?

Solution

It's because you assign each entry of str_args to a local pointer, one that goes out of scope once the loop loops.

You might want to consider strdup:

str_args[i] = strdup(buffer);

Of course, you then have to free the memory allocated by strdup.


You also have a problem when printing just after the loop, when you want to print a string, but *str_args[0] dereferences the first string. i.e. it's the first character and not a string. Remove the dereferencing operator * and it should work just fine.

OTHER TIPS

On the printf, the datatype of the parameter is incorrect Also you need to copy temporary "buffer" to allocated memory or each loop overwrites the next Code below fixes these two problems

#include<stdio.h>
#include<string.h>
main() {
    int args[] = {1, 3000};
    char *str_args[15];
    int i = 0;
    for(i; i<=((sizeof(args)/sizeof(args[0]))); i++){
               char buffer[10];
                      sprintf(buffer, "%d", args[i]);
                             str_args[i] = strdup(buffer);
    }
    printf("%s\n", str_args[0]);
}
for(i; i<=((sizeof(args)/sizeof(args[0]))); i++){

should be :

for(i=0; i<((sizeof(args)/sizeof(args[0]))); i++){//take out the `=` after >, add i=0 first.  

As the way it is originally written, i will reach 2, and cause the overrun you experienced.

(i=0 is optional since you have i initialized in the line before, but its better form to just do it in the for loop.)

You are overrunning your buffers otherwise. BTW, you do realize that there are only two items in the following array, right?

int args[] = {1, 3000};
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top