Introduction to pointers - C

Before going on further with strings let us revise the concept of pointers of which we have had a bit of feel in the chapter on functions.

There we said that pointers are variables which store address of other variables. Also address of any variable can be obtained by using ampersand (&) operator.
If we have

int j = 3;

Address of j is &j.

A pointer variable can be defined as int *k; where k is a pointer to an integer variable. Hence address of j can be assigned to k as k = &j. Contents of j can be obtained from k using ‘*’ operator.
*k gives 3
i.e. ‘*’ operator gives contents of address pointer by k.
On a similar basis, what is the address of an array? The name of the array itself is the address of the array. If we have char poem[10]; ‘poem’ gives bases address of this array. If we define character pointer as

char * ptr;
ptr = poem;

causes ptr to point to the beginning of the array poem. Contents of array can be obtained as *(ptr +0), *(ptr +1),…..
Instead of
poem[1]…. Both are same.
And an address of array elements as ptr, (ptr +1),……
Instead of
&poem [0], &poem[1],……Both are same.
Or instead of using an array of characters of given size and setting a pointer to this array, we can use pointer to character and allocate sufficient memory to it, it will be equivalent.

According to pointer logic, if ‘S’ is a pointer to character. (*S) are the contents of the address at which ‘S’ points (i.e. value). And ++S pointer to the next character (according to pointer arithmetic, which we will study later.)

pointer logic,
Initially s pointer to ‘S’ (of “SET”). (*s) = ‘S’, after s++, s points to ‘E’ Now (*s) = ‘E’
Point to be noted is that pointer is a variable but name of array is not a variable. We can say ptr++ but not poem++
This much information is sufficient for understanding the string related built in functions. Pointers and relation between arrays and pointers will be considered in detail in chapter on functions.

All rights reserved © 2020 Wisdom IT Services India Pvt. Ltd Protection Status

C Topics