Nitrogen
Nitrogen

Reputation: 63

How to pass/access a double pointer to/from a struct?

A 10x10 matrix is created as follows:

double **c = (double **)pvPortMalloc(ROW * sizeof(double*));
for (i = 0; i < ROW; i++)
    c[i] = (double *)pvPortMalloc(COL * sizeof(double));

I would like to pass double **c to a struct:

struct AMessage {
    char cMessageID;
    double (**doublePtr);
} xMessage;

At the end I want to access the struct and print the matrix on a screen, however, I am unsure how I should go about this using double pointers...

Upvotes: 0

Views: 2443

Answers (1)

John Sharp
John Sharp

Reputation: 811

Firstly, in direct answer to your question, if you define a matrix in that way and want to store its pointer in a struct, you can do it via a direct assignent. Carrying on from your example, you could make the doublePointer member of a struct AMessage point to the memory you've allocated at c simply via something like this:

struct AMessage am;
am.doublePtr = c;

But if you're wanting to create a matrix, where every row is guaranteed to have the same number of elements as any other row a better fit for representing this is a 2D array, rather than an array of pointers to other arrays.

A 2D array in C can be declared like so:

double matrix[ROW][COL];

this declares a variable called matrix, with ROW rows and COL columns.

There is nothing to stop you including this definition straight in the definition of your struct, making the definition of your struct like this:

struct AMessage
{
     char MessageId;
     double matrix[ROW][COL];
};

(Thanks to chqrlie for suggesting this)

If you definitely want a pointer to a 2D array to be in your struct (for example, you might want to have one large array referenced by two of your structs) you need to know that a 2D array in C is really a 1D array, only addressed in a certain way.

You can dynamically allocate the memory to be used for the matrix with one call to malloc:

double *c = malloc(ROW * COL * sizeof(*c));

One option for accessing element the element in column j, row i is:

double a = c[ROW * j + i];

but this is obviously a bit clunky, really, it is more convenient to access element i, j by something like this:

double a = d[j][i];

To define the pointer d that we can dereference like this we need to think of what type d[j] is. It is not, as many think a double *, rather it is a pointer to an array of ROW doubles. In C syntax you would declare d like so:

double (*d)[ROW];

Finally resolving your question, I would define your struct like this:

struct AMessage 
{
     char MessageId;
     double (*matrix)[ROW];
}

Assigning to this struct would look something like this:

struct AMessage am;
am.matrix = malloc(ROW * COL * sizeof(*am.matrix));
am.matrix[j][i] = 42; // Assigns 42 to row j, column i 

Upvotes: 1

Related Questions