user3224639
user3224639

Reputation: 11

C Beginner - Copying a char *array to another char *array

I've been struggling with this for a stupidly long amount of time. Basically, I need to copy an array of char pointers to another array of char pointers.

Right now, I have the function:

void copyArray(char *source[], char *destination[]) {
    int i = 0;

    do {
        destination[i] = malloc(strlen(source[i]));
        memcpy(destination[i], source[i], strlen(source[i]));
    } while(source[i++] != NULL);
}

This results in a segmentation fault. Could someone please help?

Thanks!

EDIT: sample program

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

// Copy the contents of one array into another
void copyArray(char *source[], char *destination[]){
    // printf("In copy array");
    int i = 0;

    do {
        destination[i] = malloc(strlen(source[i]));
        memcpy(destination[i], source[i], strlen(source[i]));
    } while(source[i++] != NULL);
}

void addToHistory(char *history[][40], char *args[]){
    int i;
    for(i = 1; i < 10; i++){
        copyArray(history[i], history[i-1]);
    }
    i = 0;
    copyArray(args, history[0]);
}

int main(void){
    char *history[10][40];
    char *args[40];

    history[0][0] = NULL;

    args[0] = "ls";
    args[1] = NULL;

    addToHistory(history, args);
}

Upvotes: 0

Views: 1820

Answers (3)

wildplasser
wildplasser

Reputation: 44230

void copyArray(char *source[], char *destination[]) {

    while ((*destiantion = *source)) {
        *destination++ = strdup( *source++ );
    }
}

BTW: it is common to make destination the first argument, just as in strcpy()

void copyArray(char *destination[], char *source[]) { ... }

Upvotes: 0

Menachem
Menachem

Reputation: 941

I think you have an off-by-one error:

do {
    destination[i] = malloc(strlen(source[i]));
    memcpy(destination[i], source[i], strlen(source[i]));
} while(source[i++] != NULL);
               ^^^

You check if i was NULL after you already used it, and then end the loop. Try replacing it with

} while (source[++i] != NULL);           // or while (source[++i]), for short

You can try logging a short message after each iteration to see where the code faults.

Edit: Is there a reason you are using memcpy() (which will not copy the terminating '\0') rather than strcpy() (which will)?

(Note to @wildplasser: I believe strdup() may not be standard C).

Upvotes: 0

barak manos
barak manos

Reputation: 30136

  1. Make sure that the last element in the source array is NULL, before you pass it to copyArray.

  2. In copyArray, put the while instead of the do, and increment i only at the end of the loop.

Instead all of the above, you can simply change i++ to ++i in function copyArray.

But it will crash if the first element in the source array passed to this function is NULL.

Upvotes: 1

Related Questions