question

DangDKhanh-2637 avatar image
0 Votes"
DangDKhanh-2637 asked DangDKhanh-2637 edited

How to using movememory function?

Hi,
I have a 5x2 matrix like this:
I want to remove the 3rd row (3 3) so I use the following code:

 1 2
 3 2
 3 3
 1 2
 2 3


 int colcount=2;
 X* begin_ = begin()+2*colcount; //(pointer to 3- row3th )
 ...
 MoveMemory(begin_ + colcount, begin_, (5-3) * colcount) * sizeof(X));
 this->row-=1;
  • 5-3 is the number rows of block to move

However I get unexpected results.
Maybe I'm misinterpreting? this is my first time using this function.
How to fix this?


Thank you

c++
· 3
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

It would be nice if you told us what the unexpected results actually were so we could help you figure out where your mistake is.

When you ask for help, it is to your advantage to provide compilable code so others can run their own tests. You haven't shown us any of the variable definitions (except for begin_) or what the begin() function does.

1 Vote 1 ·

Hi, I have a problem when moving some array parts (counting up or down) to combine them together.
but apparently, I'm not quite understanding how it work.
So I'll test some more code and come back later.


Thanks you.

0 Votes 0 ·

Hi, Thanks everyone. I was mistaken.
after swapping parameters:

   MoveMemory(begin_, begin_ +colcount, ((5-3)*colcount) * sizeof(X));

now the code works as i expected.

0 Votes 0 ·

1 Answer

RLWA32-6355 avatar image
1 Vote"
RLWA32-6355 answered

I think you will find the documentation at multidimensional-arrays-c helpful to understand how the addresses of array rows and elements are determined.

And an example -

 #define WIN32_LEAN_AND_MEAN
 #include <Windows.h>
    
 #include <stdio.h>
 #include <stdlib.h>
    
 int main()
 {
     int aInts[5][2] = {
         {1,2},
         {3,4},
         {5,6},
         {7,8},
         {9,10}
     };
    
     int Rows = _countof(aInts);
     int Cols = _countof(aInts[0]);
    
     printf("Before move\n");
     for (int r = 0; r < Rows; ++r)
         for (int c = 0; c < Cols; ++c)
             printf("aInts[%d][%d] = %d\n", r, c, aInts[r][c]);
    
     int* dest = aInts[2]; // address of row 3
     int* source = aInts[3]; // address of row 4
     SIZE_T cBytes = 2 * sizeof(int[2]); // number of rows * size of a row
     MoveMemory(dest, source, cBytes);
    
     printf("\nAfter move overwriting row 3\n");
     for (int r = 0; r < Rows; ++r)
         for (int c = 0; c < Cols; ++c)
             printf("aInts[%d][%d] = %d\n", r, c, aInts[r][c]);
    
     return 0;
 }



5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.