How to using movememory function?

DangDKhanh-2637 941 Reputation points
2021-08-26T21:57:30.203+00:00

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++
C++
A high-level, general-purpose programming language, created as an extension of the C programming language, that has object-oriented, generic, and functional features in addition to facilities for low-level memory manipulation.
3,601 questions
{count} votes

1 answer

Sort by: Most helpful
  1. RLWA32 42,001 Reputation points
    2021-08-27T01:18:26.827+00:00

    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;  
    }  
    
    1 person found this answer helpful.
    0 comments No comments