Latest web development tutorials

C pointer array

C Pointer C Pointer

Before we explain the concept of an array of pointers, let us look at an example that uses an array of three integers:

#include <stdio.h>
 
const int MAX = 3;
 
int main ()
{
   int  var[] = {10, 100, 200};
   int i;
 
   for (i = 0; i < MAX; i++)
   {
      printf("Value of var[%d] = %d\n", i, var[i] );
   }
   return 0;
}

When the above code is compiled and executed, it produces the following results:

Value of var[0] = 10
Value of var[1] = 100
Value of var[2] = 200

There may be a case, we want to make an array of storage point to an int or char or any other data type pointer. The following is a statement pointer pointing to an array of integers:

int *ptr[MAX];

Here, theptr declared as an array of pointers to integers by the MAX.Thus, ptr each element is a pointer to int values. The following example uses three integers, they will be stored in an array of pointers, as follows:

#include <stdio.h>
 
const int MAX = 3;
 
int main ()
{
   int  var[] = {10, 100, 200};
   int i, *ptr[MAX];
 
   for ( i = 0; i < MAX; i++)
   {
      ptr[i] = &var[i]; /* 赋值为整数的地址 */
   }
   for ( i = 0; i < MAX; i++)
   {
      printf("Value of var[%d] = %d\n", i, *ptr[i] );
   }
   return 0;
}

When the above code is compiled and executed, it produces the following results:

Value of var[0] = 10
Value of var[1] = 100
Value of var[2] = 200

You can also use a pointer to an array of characters to store a list of strings, as follows:

#include <stdio.h>
 
const int MAX = 4;
 
int main ()
{
   char *names[] = {
                   "Zara Ali",
                   "Hina Ali",
                   "Nuha Ali",
                   "Sara Ali",
   };
   int i = 0;

   for ( i = 0; i < MAX; i++)
   {
      printf("Value of names[%d] = %s\n", i, names[i] );
   }
   return 0;
}

When the above code is compiled and executed, it produces the following results:

Value of names[0] = Zara Ali
Value of names[1] = Hina Ali
Value of names[2] = Nuha Ali
Value of names[3] = Sara Ali

C Pointer C Pointer