C / C++ How to copy a multidimensional char array

2019-01-18 02:40发布

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

7条回答
聊天终结者
2楼-- · 2019-01-18 03:17

Note that in the following example:

char **a;

a[i] is char*. So if you do a memcpy() of a, 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 simulate A[i][j] with A[i + jwidth]. Then you can memcpy(newBuffer, oldBuffer, width * height * sizeof(*NewBuffer)).

查看更多
登录 后发表回答