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 2007-03-13 7:10 ID:hq0mUcKP

>>5
If you know x AND y, you can just malloc(x * y * sizeof(char)), then memcpy the whole block in.

If you only know x, i.e. it's a "ragged array" like argv, then iteration and strcpy/strncpy is the way to go. Keep track of the buffer length, and extend the buffer each iteration to that length using realloc (don't forget to init your pointer to NULL first). The required space for a C null-terminated string is strlen + 1, so that's what you add. If you use strncpy, make sure you set the null terminator yourself.

Can be done in a single loop, but if you prefer your memory allocated once, you can go x times through the array, using  the strlen logic above, and just malloc that big block. After that, you could probably use memcpy like in the "x AND y" situation.

If you don't know x, you're stuffed.

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