coder4lyf
coder4lyf

Reputation: 927

Can't copy string to an array of strings in C

I'm trying to traverse through my linked list and combine each of the nodes fields into a string, and then add the string into an array of strings.

void listToArray(){
   //create array of strings
    char *list[numNodes];
    int i = 0, n;

  while(head != NULL){
    // add string to array
    printf("[%d] %s %s:%d\n ", i, head->fileName, head->ip, head->port);
    n = sprintf(list[i], "[%d] %s %s:%d\n", i, head->fileName, head->ip, head->port);
    head = head->next;
    printf("%s\n", list[i]);
    i++;

 }

The printf statement works fine, which shows that it is not the fields of node that are causing the problem, but when I do my sprintf statement to copy the string into the index of the array. I get a segmentation fault.

Upvotes: 3

Views: 3604

Answers (3)

Craig Estey
Craig Estey

Reputation: 33601

list is defined but each element has no/random pointer in it. The above answers are complete but this can be simplified a bit:

void listToArray(){
    //create array of strings
    char *list[numNodes];
    char buf[5000];
    int i = 0, n;

    while (head != NULL) {
        snprintf(buf,sizeof(buf),"[%d] %s %s:%d\n ",
            i,head->fileName,head->ip,head->port);

        // add string to array
        list[i] = strdup(buf);

        // output
        fputs(list[i],stdout);

        head = head->next;
        i++;
    }
}

You only need to do a single printf/sprintf. That's the slow part. Doing a single snprintf and strdup is faster and simpler than doing 2-3 *printf calls. I'm guessing that you only want one output line per item and the rest were for debug.

Upvotes: 1

ashiquzzaman33
ashiquzzaman33

Reputation: 5741

You only declare

char *list[numNodes];

but not allocate memory for them. Before using list[i] allocate memory with malloc. To know the size of generated string from sprintf use snprintf. Thanks user3121023 for finding us this function.

void listToArray(){
   //create array of strings
    char *list[numNodes];
    int i = 0, n;

  while(head != NULL){
    printf("[%d] %s %s:%d\n ", i, head->fileName, head->ip, head->port);

    n = snprintf(NULL, 0, "[%d] %s %s:%d\n", i, head->fileName, head->ip, head->port);
    list[i] = malloc((n+1)*sizeof(char));

    n = sprintf(list[i], "[%d] %s %s:%d\n", i, head->fileName, head->ip, head->port);
    head = head->next;
    printf("%s\n", list[i]);
    i++;

 }

Upvotes: 4

antlersoft
antlersoft

Reputation: 14786

You are not initializing the array of char pointers-- sprintf is writing data to some random location.

Each char pointer should be initialized to a buffer with malloc before you call sprintf.

Upvotes: 0

Related Questions