Search code examples
cpointer-to-array

Why should we use pointer-to-arrays in C/C++?


#include<stdio.h>

#define SIZE 3

int main()
{   
    char intArrayOne[SIZE] = {'A', 'B', 'C'};

    char (*ptrToAnOneDimArray)[SIZE] = &intArrayOne;

    int i = 0;
    for(i=0 ; i<SIZE ; i++)
    {
        printf("%c ", (*ptrToAnOneDimArray)[i]);
    }
}

Output
A B C 

When should we use "ptrToAnOneDimArray" - kinds of usages in C/C++? Please give me a real-world example.

Can we avoid these kinds of complex and fuzzy usages of pointers?


Solution

  • For example, when you want to implement a dynamic multidimensional array:

    int (*ptrArr)[WIDTH] = malloc(sizeof ptrArr[0] * HEIGHT);
    

    is much better than

    int **ptrPtr = malloc(sizeof ptrPtr[0] * HEIGHT);
    for (size_t i = 0; i < HEIGHT; i++) {
        ptrPtr[i] = malloc(sizeof ptrPtr[0][i] * WIDTH);
    }
    

    for various reasons (it does actually point to a 2D array that is contiguous in memory, it requires less allocations and frees, so it's less likely that you get it wrong, etc.)