Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C pointer to pointer

Tags:

c

Does

int **p 

and

int *p[1]

mean the same thing? as both can be passed to functions allowing the change the pointer object, also both can be accessed via p[0], *p ?

Update, thanks for your help, tough Memory management seems different. does the access mechanism remain the same

*eg: p[0] becomes *(p+0) & *p (both pointing to something)

Thanks

like image 749
Akash Avatar asked Nov 25 '25 11:11

Akash


2 Answers

Not quite.

int **p;

declares a pointer p, which will be used to point at objects of type int *, ie, pointers to int. It doesn't allocate any storage, or point p at anything in particular yet.

int *p[1];

declares an array p of one pointer to int: p's type can decay to int ** when it's passed around, but unlike the first statement, p here has an initial value and some storage is set aside.


Re. the edited question on access syntax: yes, *p == p[0] == *(p+0) for all pointers and arrays.


Re. the comment asking about sizeof: it deals properly with arrays where it can see the declaration, so it gives the total storage size.

void foo()
{
    int **ptr;
    int *array[10];

    sizeof(ptr);   // just the size of the pointer
    sizeof(array); // 10 * sizeof(int *)

    // popular idiom for getting count of elements in array:
    sizeof(array)/sizeof(array[0]);
}

// this would always discard the array size,
// because the argument always decays to a pointer
size_t my_sizeof(int *p) { return sizeof(p); }
like image 100
Useless Avatar answered Nov 28 '25 02:11

Useless


To simplify things, you could factor out one level of pointers since it's not relevant to the question.

The question then becomes: what's the difference between T* t and T t[1], where T is some type.

There are several differences, but the most obvious one has to do with memory management: the latter allocates memory for a single value of type T, whereas the the former does not (but it does allocate memory for the pointer).

like image 44
NPE Avatar answered Nov 28 '25 00:11

NPE



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!