It has been a while that I used pointers and I just wanna quickly check how I can initialize an integer pointer?
a) int *tmpPtr = 0;
b) int *tmpPtr = null;
The line
int *tmpPtr = 0;
initializes the pointer value to 0, so tmpPtr is pointing "nowhere"; i.e., not a valid memory location. You have to assign a valid memory location to the pointer first like you did in the previous snippet.
There is no null
keyword in C (at least in ANSI C99). You could use a) or c).
In c) you'll not initialize pointer with null, you'll initialize it with address of local variable.
I was just refreshing my pointer knowledge and stumbled across this.
int *tmpPtr = 0;
i find it easier to think of it like this:
int *tmpPtr ;
tmpPtr = 0 ;
I 'believe' the above 2 lines are equivalent to that one line.
so basically the address to be de-referenced is set to 0 or NULL
.
Reply to your question in EDIT:
When you do this :
int tmp = 0;
int *tmpPtr = &tmp;
Mem::Copy((void*)tmpPtr, basepointer(), sizeof(int));
tmpPtr is pointing to the address of variable tmp
and it is in the stack. And notice that the "safe area" pointed by tmpPtr is the size of tmp
(which is 4 in some machine and 2 in others). If you were to copy more than sizeof(int) bytes to tmpPtr you will risk of crashing the stack.
When you do this :
int *tmpPtr = 0;
Mem::Copy((void*)tmpPtr, basepointer(), sizeof(int));
The value of tmpPtr is 0 ,so you will get a segment fault. ,which is a memory protection mechanism offered by the operation system. For example , you are not allowed to write any virtual address that is less than 4K.
Initialize your pointers which point to nothing by a null pointer constant. Any constant expressions with value 0 serve as a null pointer constant. In C NULL macro is used by convention.
You can do it any of those ways except it is NULL not null. I prefer int *p = 0; over int *p = NULL;
To eliminate some confusion I sense, setting int *p = 0 or setting MyObject *p = 0; results in the same thing.... a null pointer that will usually crash your program if you attempt to dereference it though technically it's undefined behavior. The example you have in C is different from the others because you are actually setting the pointer to point at an integer set as 0.
int *pNull = 0; int c = *pNull; // Undefined behavior. Most likely crashing your program! int a = 0; int *pInt = &a; int x = *pInt; // x equals 0 a = 10; int y = *pInt; // y equals 10