Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

copy an array in c

Name: Anonymous 2007-03-12 22:30 ID:016HOAcL

I have a function, it accepts a char**, what is the quickest and most efficient way of making a local copy of the array in the function scope?

That is, i have , for example:

void funk(char **x){

char **b;

/*How do i make a separate copy of x to b?*/
}

Take pity on me internets, I'm a noob :) Thanks.

Name: Anonymous 2012-05-29 0:02

>>51

I forgot nulls on strings


// assuming x is a null terminated array of null terminated strings
// untested
void funk(char **x) {
    // calculate length of x
    size_t len;
    for (len = 0; x[len]; ++len);
    // allocate copy
    char **copy = malloc((len + 1) * sizeof(*x));
    // copy over strings
    for (size_t i = 0; i < len; ++i) {
        size_t _len = strlen(x[i]);
        copy[i] = malloc(_len + 1);
        strcpy(copy[i], x[i]);
        copy[_len] = 0;
    }
    // add null terminator
    copy[len] = 0;
}

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List