I'm looking for a smart way to copy a multidimensional char array to a new destination. I want to duplicate the char array because I want to edit the content without changing the source array.
I could build nested loops to copy every char by hand but I hope there is a better way.
Update:
I don't have the size of the 2. level dimension. Given is only the length (rows).
The code looks like this:
char **tmp;
char **realDest;
int length = someFunctionThatFillsTmp(&tmp);
//now I want to copy tmp to realDest
I'm looking for a method that copies all the memory of tmp into free memory and point realDest to it.
Update 2:
someFunctionThatFillsTmp() is the function credis_lrange() from the Redis C lib credis.c.
Inside the lib tmp is created with:
rhnd->reply.multibulk.bulks = malloc(sizeof(char *)*CR_MULTIBULK_SIZE)
Update 3:
I've tried to use memcpy with this lines:
int cb = sizeof(char) * size * 8; //string inside 2. level has 8 chars
memcpy(realDest,tmp,cb);
cout << realDest[0] << endl;
prints: mystring
But I'm getting a: Program received signal: EXC_BAD_ACCESS
Note that in the following example:
a[i]
ischar*
. So if you do amemcpy()
ofa
, you're doing a shallow copy of that pointer.I would ditch the multi-dimensional aspect and go with a flat buffer of size
nn
. You can simulateA[i][j]
withA[i + jwidth]
. Then you canmemcpy(newBuffer, oldBuffer, width * height * sizeof(*NewBuffer))
.