Search code examples
c++pointersmallocpointer-to-member

Malloc, Pointers and Variables


First of, thank you for taking your time. I am trying to understand what the particular code showed below is trying to do so as to convert them into python. The first line is to allocate memory to pointer (aPointContour) which I am aware python do not have. The second line is to obtain random number within iContourLenght. The third line allocates value (2*aPointContour[iRandomPoint1].x + aPointContour[iRandomPoint1].y) to matrix (pMatA) at row 0 and column 0.

My question:

1) What is "aPointContour[iRandomPoint1].x" trying to do?

2) The purpose of .x .y?

My thought:

1) Accessing memory located at "iRandomPoint1" within pointer, "aPointContour". The value needed to be placed into matrix "pMatA" is "2*iRandomPoint1", and according to the code below accessing memory should not give us "iRandomPoint1" value?

2) Is .x and .y part of Cvpoint or in general used as a member of pointer "aPointContour"? If it's a member will it be for reference purpose only or actual mathematical significance?

My apologies for the long post, really hope someone could help me out. Thanks you any kind sir or madam in advanced! :)

// C++
CvPoint *aPointContour = (CvPoint *) malloc(sizeof(CvPoint) * iContourLength);
iRandomPoint1 = (int)((double)rand() / ((double)RAND_MAX + 1) * iContourLength);
cvmSet(pMatA, 0, 0,2* aPointContour[iRandomPoint1].x + aPointContour[iRandomPoint1].y)

Solution

    1. aPointContour is a pointer to an array of CvPoint objects. aPointContour[iRandomPoint1].x uses iRandomPoint1 as the index into the array, then accesses the x member variable within that object.

    2. .x and .y access member variables of objects. This is analogous to accessing object properties in Python. These are members of the CvPoint class. Look for a declaration of class CvPoint or struct CvPoint somewhere in the code (probably in a header file), it will declare all the member variables and functions.

    The only real problem with this code is that it's using uninitialized values of the array elements. malloc() allocates memory, but it doesn't fill it in with anything predictable. So unless you've left out code that fills in the array, when it accesses aPointContour[iRandomPoint1].x and aPointContour[iRandomPoint1].y, undefined behavior occurs.