Search code examples
cpointersstructuredouble-pointer

Double pointer to struct


I have seen this program on the Intel website, but I don't understand some lines. If you couldn't understand the program I appreciate it if you suggest some material to analyze such programs.

The program is written in C language and declares two structures with the name of Coefficients and Roots, then instantiates double pointers to both of them with 0. If Coef_set and Root_set are double pointers, why they refer to the same number zero?

The way the program uses malloc is also strange, because it uses double-pointer to structure for type casting (I mean here: Coef_set = (struct Coefficients **)) and a pointer to structure in the sizeof function. (I mean here: sizeof(struct Coefficients *)). Then in a for loop gives the parameters of a, b, c, x1, and x2 the value of zero and in the next for loop gives other numbers to them. Why it assigns the numbers two times?

// Quadratic Equation: a*x^2 + b*x + c = 0
struct Coefficients {
    float a;
    float b;
    float c;
} coefficients;

struct Roots {
    float x1;
    float x2;
} roots;


struct Coefficients ** Coef_set=0;
struct Roots ** Root_set=0;

Coef_set = (struct Coefficients **) malloc(N * sizeof(struct Coefficients *));
Root_set = (struct Roots **) malloc(N * sizeof(struct Roots *));

for (i=0; i<N; i++)
{
    Coef_set[i] = (struct Coefficients *) malloc(sizeof(struct Coefficients));

    Coef_set[i]->a = 0;
    Coef_set[i]->b = 0;
    Coef_set[i]->c = 0;
    
    Root_set[i] = (struct Roots *) malloc(sizeof(struct Roots));

    Root_set[i]->x1 = 0;
    Root_set[i]->x2 = 0;
}

// Initialize the arrays
for (i=0; i<N; i++)
{
    Coef_set[i]->a = (float)(i % 64) + 1.0;
    Coef_set[i]->b = (float)(i % 64) + 101.0;
    Coef_set[i]->c = (float)(i % 32) - 33.0;

    Root_set[i]->x1 = 0;
    Root_set[i]->x2 = 0;
}

Solution

  • The lines struct Coefficients ** Coef_set=0; and struct Roots ** Root_set=0; do not set the pointers “to refer to the same number zero.” When used to give a value to a pointer, the constant 0 serves as a null pointer. Each pointer is set to a value, called the null pointer, that indicates it is not pointing to any object.

    The following statements, Coef_set = (struct Coefficients **) malloc(N * sizeof(struct Coefficients *)); and Root_set = (struct Roots **) malloc(N * sizeof(struct Roots *));, each allocates memory and sets one of the pointers to point to that memory. Because if this, the initialization of the pointers to the null pointer is of no consequence; that null pointer value is immediately overwritten with a pointer to allocated memory.