Arrays and Pointers
Arrays and pointers are closely related.
Array name is like a constant pointer.
Example:
Declare an array b[5] and a pointer ‘bPtr’
bPtr = b; // To set them equal to one another
// The array name(b) is actually the address of the first element of the array
bPtr = &b[0]; // Explicitly assigns bPtr to the address of first element of b.
To access element b[3]
x = *( bPtr + 3) // Where n is the offset. Called pointer/offset notation
x = bPtr[3] // Called pointer/subscript notation
// bPtr[3] same as b[3]
x = *(b + 3) // Performing pointer arithmetic on the array itself
Strong relation between pointers and arrays
Pointers and arrays can be used interchangeably.
The array name is equivalent to the address of the first element in the array.
Example:
int a[10];
int *pa;
pa = &a[0]; //is equivalent to pa = a
So,
a[1] *(pa + 1) pa[1] *(a + 1)
&a[1] pa + 1 a+1
a[i] *(pa+1) pa[i] *(a+i)
&a[1] pa+1 a+i
a[i]+= 5 *(pa+i)+= 5pa[i]+= 5
Example:
f(int s[]) f(int *s)
{.... {....
} }
Arrays can contain pointers.
For example: an array of strings.
char *suit[4] = {“Hearts”, “Diamonds”, “Clubs”, “Spades”};
Strings are pointers to the first character
Char * - each element of the suit is a pointer to a char
The strings are not actually stored in the array suit, only pointers to the strings are stored.
Pointer to Void
‘void’ type pointer is a generic pointer, which can be assigned to any data type without cast during compilation or runtime. ‘void’ pointer cannot be referenced unless it is cast.
Instead of declaring different types of pointer variable it is feasible to declare a single pointer which can act as an integer pointer or a character pointer.
Syntax:
void *pointer_name;
Example:
#include<stdio.h>
int main()
{
void* p;
int x =7;
float y =23.5;
p = &x; // p now points to an int value
printf(“x contains: %d\n”, *((int *)p));
p = &y; //p now points to a float value
printf(“y contains: %f\n”, *((float *)p));
}
OUTPUT
x contains 7
y contains 23.500000