C Programming Language


Pointer


Pointer is a Variables that can store addresses are called pointers, and the address that’s stored in a pointer is usually that of another variable.The word pointer is also used to refer to just an address.

How Pointer Works ?

 

How pointer works ?

You have a pointer pnumber that contains the address of another variable, called number, which is an integer variable containing the value 99. The value that’s stored in pnumber is the address of the first byte of number.

 

Declaring Pointers :

You can declare a pointer to a variable of type int with the following statement:

int *pnumber;

The type of the variable with the name pnumber is int*. It can store the address of any variable of type int. Note that you can also write the statement like this:,

int* pnumber;

This is exactly the same as the previous statement in its effect. You can use either notation, but it is best to stick to one or the other.

You can initialize pnumber so that it doesn’t point to anything by rewriting the declaration like this:

int *pnumber = NULL;

NULL is a constant that’s defined in the standard library and is the equivalent of zero for a pointer. NULL is a value that’s guaranteed not to point to any location in memory. This means that it implicitly prevents the accidental overwriting of memory by using a pointer that doesn’t point to anything specific

 

Accessing a Value Through a Pointer :

You use the indirection operator, *, to access the value of the variable pointed to by a pointer. This operator is also referred to as the dereference operator because you use it to “dereference” a pointer. Suppose you declare the following variables:

int number = 15;
int *pointer = &number;

 

Example :

Output :

number's address: 000000000012ff0c
number's value: 10

pnumber's address: 000000000012ff00
pnumber's size: 8 bytes
pnumber's value: 000000000012ff0c
value pointed to: 10

Hard Line Explanations :
printf("pnumber's address: %p\n", (void*)&pnumber); // Output the address

Here, you output the address of pnumber. Remember, a pointer itself has an address, just like any other variable. You use %p as the conversion specifier to display an address, and you use the & (address of) operator to reference the address that the pnumber variable occupies. The cast to void* is to prevent a possible warning from the compiler. The %p specification expects the value to be some kind of pointer type, but the type of &pnumber is “pointer to pointer to int.”

printf("pnumber's size: %d bytes\n", sizeof(pnumber)); // Output the size

You use the sizeof operator to obtain the number of bytes a pointer occupies, just like any other variable, and the output on my machine shows that a pointer occupies 8 bytes, so a memory address on my machine is 64 bits.