An array of integers and an array of int pointers that point to the first array, does this make sense?

StackOverflow https://stackoverflow.com/questions/22131632

  •  19-10-2022
  •  | 
  •  

Question

I am experimenting to set up two arrays, let's say array myflags_init and array tripleP; both arrays are two dimenstional, because tripleP is an array of pointers that point to the corresponding index in array myflags_init. Below is my code, and the compiling works fine. I would like to discuss whether this makes sense, as the syntax is a bit crazy to me (e.g. int **tripleP[2] for declaring the two-dimenstional array tripleP of int pointers).

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main()
{
    int m;
    for (m = 0; m < 20; m++)
    {
    int *myflags_init[2];
    myflags_init[0] = (int *) calloc(2, sizeof(int));
    myflags_init[1] = (int *) calloc(2, sizeof(int));

    int r, k;
    for (r = 0; r < 2; r++)
    {
        for (k = 0; k < 10; k++)
        {
            myflags_init[r][k] = 0;   /* initialize the two-d array to 0 */
        }
    }

    int false_num = 0;

    int **tripleP[2];
    tripleP[0] = (int **) calloc(10, sizeof(int **));
    tripleP[1] = (int **) calloc(10, sizeof(int **));

    for (r = 0; r < 2; r++)
    {
        for (k = 0; k < 10; k++)
        {
            tripleP[r][k] = &myflags_init[r][k];     /* tripleP pointers point to the corresponding index in myflags_init */
        }
    }
    }

    return 0;
}
Was it helpful?

Solution

int **tripleP[2];
tripleP[0] = (int **) calloc(10, sizeof(int **));
tripleP[1] = (int **) calloc(10, sizeof(int **));

That works, but shouldn't be written like this. You want to allocate an array of int*, not int**. However it just so happens that both types have the same size (they are both pointers) and thus this will work anyway. But for clarity replace it with this:

int **tripleP[2];
tripleP[0] = (int **) calloc(10, sizeof(int *));
tripleP[1] = (int **) calloc(10, sizeof(int *));

Also the initialization of myflags_init[0] and myflags_init[1] is wrong, because you allocated for 2 elements for each, but try to initialize 10 of them:

myflags_init[0] = (int *) calloc(2, sizeof(int));
myflags_init[1] = (int *) calloc(2, sizeof(int));
//...
for (k = 0; k < 10; k++)

Also you don't need to set them manually to zero. That is exactly what calloc already does for you (in contrast to malloc).

And the outer for-loop seems rather pointless, not to mention the memory leak, because you keep allocating new memory but never call free.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top