#include <stdio.h>
#include <stdlib.h>
int main(){
int **p = NULL;
printf("%d\n", *p); //Why is this line giving an error???
//What kind of error is it?
//What does "*p" do ?
//What can "*p" do ?
//What is "*p" ?
//When does the compiler allocate a memory address to it?
//I usually use the codes below:
int a = 60;
int *p1 = NULL;//a pointer
int **p2 = NULL;//a double pointer
p1 = &a; //point to an integer varible a
p2 = &p1; //point to a pointer p1
system("pause");
return 0;
}
Just think "What is [**]p?". The answer would very clearly be: **p is an integer, *p is a pointer to an integer and p is a pointer to a pointer [to an integer]. All your questions should now solve themselves.
int **p = NULL;
printf("%d\n", *p); //Why is this line giving an error???
p is a pointer to a pointer to an int, it's just like p2 that appears later on. In this case it's initialised to null.
Whe you pass *p to printf, you're dereferencing p. That is, you're getting the value that p points to. In your case, you've already told it that it doesn't point anywhere, then you try to dereference it. This is an error, and your memeory address space is mapped such that this interrupts the program (as it's such a common error to dereference null).
NULL means 0. That is the case and even for some old c compilers NULL should mean 0.
That is that for variables as int it's obvious what it means (just a value equal to zero) but for pointers it has some special meaning since it means: Not pointing to anything.
You can safely use 0 instead but it's more clear sometimes to use NULL.
NULL is a alias of (void*)0, there is no difference in the value.
The thing you have to understand is that NULL cannot be dereferenced.
But at line 10 you give a value to p, the adress of p1.
So at line 14 it will print the value in the variable p1 which is the adress of a.
#include <stdio.h>
#include <stdlib.h>
int main(){
int a[2][2] = {{4, 5}, {6, 7}};
int **p;
int *p1 = NULL;
p1 = &a[0][0];
*p = &a[0][0]; //Why is this line giving an error?
system("pause");
return 0;
}
#include <stdio.h>
#include <stdlib.h>
int main(){
int a[2][2] = {{4, 5}, {6, 7}}; //This array is initialized.
int **p = NULL; //But... For a pointer... Is this pointer really initialized on this line?
int *p1 = NULL;
p1 = &a[0][0];
p = (int **)&a[0][0]; //???This line...
//Does the compiler really initialize the pointer or allocate memory address for it?
*p = &a[0][0]; //This line isn't giving an error.
printf("*p = %d\n", *p);
*p = (int *)6;
printf("p = %d\n", p);
printf("*p = %d\n", *p);
system("pause");
return 0;
}
Dereferencing an uninitialized pointer is not defined and might still crash the program.
But there is a new question...
When does p really be initialized?