Home > other >  Yet another C pointer to array question
Yet another C pointer to array question

Time:04-24

I haven't written C for over 25 years and evidently I've forgotten a lot, and the compilers are now far more strict than they used to be. Consequently, I'm struggling and failing to create a dynamically allocated array of pointers to arrays of 8 unsigned char.

I believe I need a single variable that's a pointer. I expect that variable to be assigned at runtime to point at a dynamically allocated array of pointers. Each of the resulting pointers would then be assigned to point to an array of 8 unsigned char.

I think that the variable declaration for my array should be:

int (**arr)[8];

but I'm failing to work out how to allocate the storage.

For the first step I have tried a number of variations on this idea:

arr = new (int*[8])[4];

but all have been rejected as type incompatible, or flat out syntax errors. In desperation, I also tried:

arr = malloc(4 * sizeof(void *));

which was rejected with "cannot convert ‘void*’ to ‘int (**)[8]’" so I tried a cast:

arr = (int**[8])malloc(4 * sizeof(void *));

Which still failed.

EDIT: In light of comments so far, first, I'm writing in C , for an ESP32 device, and have now progressed to these efforts (still failing)

arr = new (int(*)[8])[4]; // array bound forbidden after parenthesized type

and

arr = new (int(*)[])[4]; // cannot convert ‘int (**)[]’ to ‘int (**)[8]’

It's clear from the comments that "I need to relearn a ton of stuff", and even "this isn't the best way of doing it", but for now I would like to just get the job done. Can anyone simply tell me a) if my variable declaration is sound, and b) how do I allocate the initial array of pointers?

CodePudding user response:

I believe you want to get to know ** double pointer and how to use them.

// explanation of what double pointer is.

    int **arr1; //double pointer: is a pointer to point to pointer
 
    // example
    int* p = new int(1);
    arr1 = &p; // points to pointer int*, note the "&" affront which returns the memory address of p.
    arr1 = new int*[10]; // points to int*, "new" returns the memory address of newly allocated memory space.


// harder example, how to point to a double array [][]
    int num_rows = 10;  
    arr1 = new int*[num_rows];

    for (int i = 0; i < num_rows;   i)
    {

        int num_cols = i   1; // the column length can be different for each row
        arr1[i] = new int[num_cols];

        for (int j = 0; j < num_cols;   j)
            arr1[i][j] = i;

    }

note that ** points not only those rows with fixed length, it can point to unequal length of data rows as shown in example. pay care to track the row lengths or just use double array.

  • Related