• C

References to pointers

In C++ all references (by default) are initialized. Is it possible in C to have a reference to a pointer in which the pointer is null? Or does the pointer have to point to memory for you to take the reference of it?

e.g.

<type>* ptr1 = NULL;
<type>  ptr2;

ptr2 = &ptr1;

ipaman
ipamanAsked:
Who is Participating?
 
Sjef BosmanGroupware ConsultantCommented:
Change your code:

<type>* ptr1 = NULL;
<type>**  ptr2; // note **

ptr2 = &ptr1;
0
 
Sjef BosmanGroupware ConsultantCommented:
No problems with that. The variable ptr1 itself exists, so you can take it's address.
0
 
PaulCaswellCommented:
A pointer can point to anything or nothing or even a page-fault location. It is only when you dereference it that what it points to is accessed.

E.G.

char * a = (char *)1; // a points to an invalid memory location.
a += 1; // still invalid but no problem as I am not dereferencing.
char b [128]; // b is valid.
b[(int)a] = 'b'; // Valid as 'a' has the value 2;
a[(int)b] = '2'; // Also valid but you wouldnt want to do this.
a[0] = '0'; // Will probably page fault.

Paul
0
 
ipamanAuthor Commented:
bosman,

...but if you then try to dereference ptr2 (ptr2->...) you will wind up with an exception thrown,
correct?

0
 
Sjef BosmanGroupware ConsultantCommented:
Dereferencing ptr2 won't work, at least not the way you typed. Ptr2 is a pointer to a pointer to some type, so you'll need
    (*ptr2)->
to get something from the structure ptr1 points to. And ptr1 points to the location zero, usually not given to a user program as a writable location. The expression
    *ptr2
will work though, because that will get the content of ptr1 that contains NULL.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.