PDA

View Full Version : 2D pointer assignment



uz_qt
16th October 2013, 10:00
Hello,

I have two 2D pointers.
float **A;
float **B;
both have two rows and each row has 10 columns.
I would only like to copy the elements of B[1] to A[0] that is from second row of B to first row of A.

So, I wrote:


A[0] = B[1];

This does not work! The above assignment copies all the elements from both the rows of B to A.
What am I missing??

myta212
16th October 2013, 11:12
Hi,
You need to give size of copying data.
Example A and B as 2D integer array have size n rows and m columns.
So, if you wan to copy element from B[1] to A[0], you can use command :

memcpy(A[0], B[1], m*sizeof(int))

The other method is you can loop the value from your array.
But, I think the first method is more simple.

best regards,

Toto

uz_qt
16th October 2013, 12:00
@myta212: Thanks for ur response.

But the problem is that it should be done during run time. The indices(rows) which should be shifted are updated according to the selection in QComboBox.
And the processing is done frame-wise in real time. By using memcpy I only copy one frame. But I want to shift the entire row (which is computed during run time frame by frame).

Therefore, I would only like to switch the row numbers. There is any solution which suits my requirement?

ChrisW67
17th October 2013, 06:12
Your original attempt did not copy anything at all, it just changed a pointer (and caused a memory leak in all likelihood).



A[0] = B[1];
This does not work! The above assignment copies all the elements from both the rows of B to A.

If it does what you describe then you don't have the pointer to a list of pointers to int you think you have.


But the problem is that it should be done during run time.
Why do you think using memcpy() cannot meet this requirement? The example shown above copies an entire row.

You have a C++ compiler, why are you using C-style structures with all of their memory allocation and sizing pitfalls? The way to do this is with a QVector<QVector<int> > or a similar structure using the C++ standard library or Boost.


QVector<QVector<int> > A;
QVector<QVector<int> > B;
A.resize(rows);
B.resize(rows);
for (int r = 0; r < rows; ++r) {
A[r].resize(cols);
B[r].resize(cols);
for (int c = 0; c < cols; ++c) {
A[r][c] = 0;
B[r][c] = c;
}
}
qDebug() << "A Before" << A;
qDebug() << "B Before" << B;
AA[0] = BB[1];
qDebug() << "A After " << A;
qDebug() << "B After " << B;
// A Before QVector(QVector(0, 0, 0) , QVector(0, 0, 0) )
// B Before QVector(QVector(0, 1, 2) , QVector(0, 1, 2) )
// A After QVector(QVector(0, 1, 2) , QVector(0, 0, 0) )
// B After QVector(QVector(0, 1, 2) , QVector(0, 1, 2) )