0

I've 2D arrays as below,

float** src;

which is filled with some values.

float des[x][x];

x is equal to the number of rows in src array.

So basically i want to generate a static 2D array from a dynamic 2D array. I tried to use memcpy(&des, src, x), But it gives wrong result.

Any suggestions??

2
  • Need copy each rows. Commented Aug 2, 2017 at 5:53
  • float** is not contiguous in memory. You can't use memcpy only once. Try to understand what ** means. You can do this with memcpy x times Commented Aug 2, 2017 at 5:53

2 Answers 2

1

Well, 2D array element's are stored in memory in a row, |x| == memory cell

1.row |x|x|x|x|x|x| 2.row |x|x|x|x|x|x| 3.row |x|x|x|x|x|x|

while every pointer of array of pointer can point on completely different address in memory. For example first pointer points on array on adress 100, second points on adress 248, third on array on adress 2.

3.row |x|x|x|x|x|x| |?|?|?| 1.row |x|x|x|x|x|x| |?|?|?|?| 2.row |x|x|x|x|x|x|

So you could use memcpy on every row of arrays separately, or copy them element by element.

Hope it helps.

Sign up to request clarification or add additional context in comments.

Comments

0

There are 2 problems with your memcpy:

1. src rows are not necessarily continuous

Consider:

#define x 2
float src_row_0[x] = { 0.0f, 0.1f };
float src_row_1[x] = { 1.0f, 1.1f };
float * src_rows[x] = { src_row_0, src_row_1 };
float ** src = src_rows;

There is no guarantee that rows are next to each other in memory. So you cannot copy bytes with single memcpy. Same applies even if you allocated srcrows with malloc.

You'll need to copy each row separately.

2. Size x is not enough to copy all bytes

memcpy copies number of bytes, not number of elements. Single float variable is usually more than 1 byte in size. Simply passing x to memcpy is not enough. You'll need to multiply each number of items by size of an single element.

Fixing the copy

Corrected copy would look something like this:

for(int i=0; i<x; ++i) {
    memcpy(&dst[i], src[i], x * sizeof(float));
}

Example on Ideone.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.