Ovidiu Firescu
Ovidiu Firescu

Reputation: 405

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.

Upvotes: 2

Views: 684

Answers (2)

dbush
dbush

Reputation: 223699

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;
    }
 }

Upvotes: 4

SoronelHaetir
SoronelHaetir

Reputation: 15164

Return a from a function, save it as a class member, it is just like any other variable. If you want to save the contents of the arrays then do that (but that is not what I could call saving a double pointer -- by the way the usual description is "pointer-to-pointer").

Upvotes: 0

Related Questions