| Previous | Home | Next |
Let us consider the following example, which makes use of an array of 3 integers:
#include <stdio.h>
const int MAX = 3;
void main ()
{
int var[] = {12, 400, 800};
int i;
for (i = 0; i < MAX; i++)
{
printf("Value of var[%d] = %d\n", i, var[i] );
}
}
Value of var[0] = 12
Value of var[1] = 400
Value of var[2] = 800
# Following is the declaration of an array of pointers to an integer
There may be a situation when we want to maintain an array, which can store pointers to an int or char or any other data type available.
int *ptr[MAX];
Declares ptr as an array of MAX integer pointers. Thus, each element in ptr, now holds a pointer to an int value.
#include <stdio.h>
const int MAX = 3;
int main ()
{
int var[] = {12, 400, 800};
int j, *ptr[MAX];
for ( j = 0; j < MAX; j++)
{
ptr[j] = &var[j]; /* assign the address of integer. */
}
for ( j = 0; j < MAX; j++)
{
printf("Value of var[%d] = %d\n", j, *ptr[j] );/* value of variable */
printf("Value of var[%d] = %d\n", j, ptr[j] ); /* address of variable */
}
return 0;
}
Value of var[0] = 10
Value of var[0] = 1570429008
Value of var[1] = 100
Value of var[1] = 1570429012
Value of var[2] = 200
Value of var[2] = 1570429016
# Use an array of pointers to character to store a list of strings as follows:
#include <stdio.h>
const int MAX = 4;
int main ()
{
char *student[] = {
"ABC",
"XYZ",
"PQR",
"MNO",
};
int i = 0;
for ( i = 0; i < MAX; i++)
{
printf("Name of student[%d] = %s\n", i, student[i] );
printf("Address value of student[%d] name = %d\n", i, *student[i] );
}
return 0;
}
Name of student[0] = ABC
Address value of student[0] name = 65
Name of student[1] = XYZ
Address value of student[1] name = 88
Name of student[2] = PQR
Address value of student[2] name = 80
Name of student[3] = MNO
Address value of student[3] name = 77
| Previous | Home | Next |