Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C / C++ How to copy a multidimensional char array without nested loops?

Tags:

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

like image 741
dan Avatar asked Feb 09 '10 00:02

dan


1 Answers

You could use memcpy.

If the multidimensional array size is given at compile time, i.e mytype myarray[1][2], then only a single memcpy call is needed

memcpy(dest, src, sizeof (mytype) * rows * columns); 

If, like you indicated the array is dynamically allocated, you will need to know the size of both of the dimensions as when dynamically allocated, the memory used in the array won't be in a contiguous location, which means that memcpy will have to be used multiple times.

Given a 2d array, the method to copy it would be as follows:

char** src; char** dest;  int length = someFunctionThatFillsTmp(src); dest = malloc(length*sizeof(char*));  for ( int i = 0; i < length; ++i ){     //width must be known (see below)     dest[i] = malloc(width);      memcpy(dest[i], src[i], width); } 

Given that from your question it looks like you are dealing with an array of strings, you could use strlen to find the length of the string (It must be null terminated).

In which case the loop would become

for ( int i = 0; i < length; ++i ){     int width = strlen(src[i]) + 1;     dest[i] = malloc(width);         memcpy(dest[i], src[i], width); } 
like image 156
Yacoby Avatar answered Sep 21 '22 17:09

Yacoby