Search code examples
cpointersdouble-pointer

Double pointer addresses


I created and allocated a double pointer like this:

 int **a;
 a = (int**)malloc(10 * sizeof(int *));
 for (int i = 0; i < 10; i++)
     *(a+i) = (int *)malloc(10 * sizeof(int));

And then I initialized it for example like this:

for (int i = 0; i < 10; i++) {
    for (int j = 0; j < 10; j++) {
        **a = 1;
         (*a)++;
    }
    a++;
 }

My problem and question is how can I save the address'es of my double pointer?At this moment I lost them and can't use them anymore.


Solution

  • Don't use explicit pointer arithmetic and dereferencing when array subscripting will do:

     int rows = 10, cols = 10
     int **a;
     // don't cast the return value of malloc
     a = malloc(rows * sizeof(*a));
     for (int i = 0; i < rows; i++)
         a[i] = malloc(cols * sizeof(**a));
    
    ...
    
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            a[i][j] = 1;
        }
     }