-4

I wanted to copy the content of a two dimensional array into another two dimensional char array. I used the following for loop with memcpy but it is not working as desired. So I have two questions.

  1. What is wrong with this code? and
  2. Is there a way to do it without use of iteration?

    for (int i = 0; i < count; i++) {
        memcpy(&buf_copy[i], buf[i], sizeof(buf[i]));
    }
    

Both buf and buf_copy are 2d dynamic char arrays.

Edit: declarations of the arrays

char **buf;
char **buf_copy;

EDIT 2: Here is how memory is allocated to them

void intit_buf()
{
    buf = (char**)malloc(BUFFER * sizeof(*buf));
    for (int i = 0; i < BUFFER; i++)
        buf[i] = (char*)malloc(sizeof(char) * 33);

    //initialize buf_copy
    buf_copy = (char**)malloc(BUFFER * sizeof(*buf_copy));
    for (int i = 0; i < BUFFER; i++)
        buf_copy[i] = (char*)malloc(sizeof(char) * 33);
}
mch
  • 9,424
  • 2
  • 28
  • 42
John_D
  • 29
  • 6

1 Answers1

1

What is wrong with this code?

The first and last parameters of the function call.

Change this:

memcpy(&buf_copy[i], buf[i], sizeof(buf[i]));

to this:

memcpy(buf_copy[i], buf[i], 33);

since you need to give the size of the column, not the size of a pointer!

Moreover, notice that you need to pass buf_copy, just like you did for buf, without taking the address of it or something, since memcpy() expects pointers for its two first parameters, and buf_copy[i] and buf[i] are pointers already.

Is there a way to do it without use of iteration?

It cannot be done without ireation because malloc() may not have returned contigeous memory. Read more in C / C++ How to copy a multidimensional char array without nested loops?


PS: Unrelated to your problem, but in general: Do I cast the result of malloc? No!

gsamaras
  • 71,951
  • 46
  • 188
  • 305
  • What do you think about my second question though? – John_D Dec 04 '17 at 08:46
  • Now i can accept your answer. Earlier I didn't want my question marked "answered" soon because I was waiting for reply regarding my second question. And the dimension of the array is known at compile time. Thanks for the link – John_D Dec 04 '17 at 09:00
  • More general, as soon as we talk about an array of pointers to rows which are dynamicallt allocated, it cannot be done without iteration. `char a[10][20]` is a contigeous block of memory, so is `char b[n][m]`. But `char **c` with `c=malloc(n*sizeof(char *))` will not result in a 2-dimensional array of contigeous memory. – Paul Ogilvie Dec 04 '17 at 09:07
  • Right, @PaulOgilvie thanks for helping me improve the answer! – gsamaras Dec 04 '17 at 09:14