A variable's memory location or address can be accessed using ampersand &
operator.
The following code prints the memory address of the variables.
#import <Foundation/Foundation.h> int main () { int var1; char var2[10]; NSLog(@"Address of var1 variable: %x\n", &var1 ); NSLog(@"Address of var2 variable: %x\n", &var2 ); return 0; }
A pointer is a variable whose value is the address of another variable.
The general form of a pointer variable declaration is:
type *var-name;
type
is the pointer's type and it must be a valid Objective-C data type
var-name
is the name of the pointer variable.
*
tells the compiler that it is a pointer.
The following code has some valid pointer declaration.
int *ip; /* pointer to an integer */ double *dp; /* pointer to a double */ float *fp; /* pointer to a float */ char *ch /* pointer to a character */
The data type of a pointer is that type of variable that the pointer points to.
The actual the value of all pointers is a long hexadecimal number that represents a memory address.
#import <Foundation/Foundation.h> int main () { int var = 20; /* variable declaration */ int *ip; /* pointer declaration */ ip = &var; /* store address of var in pointer variable*/ NSLog(@"Address of var variable: %x\n", &var ); NSLog(@"Address stored in ip variable: %x\n", ip ); NSLog(@"Value of *ip variable: %d\n", *ip ); return 0; }
We can assign a NULL
to a pointer variable.
NULL is called null pointer.
#import <Foundation/Foundation.h>
int main ()
{
int *ptr = NULL;
NSLog(@"The value of ptr is : %x\n", ptr );
return 0;
}