C109: Pointers

Pointer is a special type of variable that points to another variable. Like a variable it is a location in a memory to store data. Data that it stores is an address. Like any other variables, pointer need to be declared.

dataType *pointerName;

data type is same as the data type of the variable its pointing to. The data type can be int, float, double or char. A pointer name is like a normal variable but a asterisk sign '*' is places before the pointer name, to tell the compiler that it is a pointer.

The value assigned to a pointer is a long hexadecimal number that represents the address of the variable it is pointing to. Following is syntax for assigning an address to pointer:

pointerName = &variableName;

Following example shows how address of varA is assigned to ptr. Both varA and ptr is integer.

int *ptr;
int varA;

varA = 213
ptr = &varA;

to display the value stored by variable pointed by pointer

printf("Variable value pointed by pointer: %d\n", *ptr);

this will output

Variable value pointed by pointer: 231

if we write ptr without the asterisk like shown in code below, we are actually referring to the address this pointer stores.

printf("Variable value pointed by pointer: %d\n", ptr);

it will display the address of the varA. This is one of the common misunderstanding we might face when using pointer.

Variable value pointer by pointer : d3efc7d8

the address printed in the previous code is suppose to be same as when we write the following code:

printf("Address of varA : %d\n", &varA);

and the output is:

Address of varA : d3efc7d8

We can also do arithmetic operations on pointer. For example, we can increment the address to next address location in memory by adding 1.





Comments

Popular posts from this blog

Drawing Simple Pie Chart

VB.net connecting to SQL Server

VB.net