C- pointer array

ww‮.w‬lautturi.com
C- pointer array

In this tutorial, we will learn about pointer arrays in the C programming language.

declare variables

In this tutorial, we will declare four integer variables.

//integer variables
int num = 10;
int score = 12;
int run = 123;
int goal = 3;

We can express it in memory as follows.
We assume that an integer value takes up 2 bytes, so each variable takes up 2 bytes in memory.
These storage spaces are filled with integer values, which are not shown in the above figure.

Pointer array

Since we have four integer pointers, we can create four independent integer pointer variables, such as
“ptr1”、“ptr2”、“ptr3” and “ptr4”。

Alternatively, we can declare a single integer array pointing to ptr variables, which will point to four variables.
In the following example, we will declare an integer pointer ptr array of size 4.

//array of integer pointers
int *ptr[4];

Assign address to pointer array

We can use the address operator "&" to obtain the address of the variable, and then store the address in the pointer array.

//assign address of variables to ptr
ptr[0] = #
ptr[1] = &score;
ptr[2] = &run;
ptr[3] = &goal;

Accessing the value of a variable through a pointer array

To access the value of a variable through a pointer array, we must use the address operator "*" .

//print value
printf("num: %d\n", *ptr[0]);
printf("score: %d\n", *ptr[1]);
printf("run: %d\n", *ptr[2]);
printf("goal: %d\n", *ptr[3]);

full code

#include <stdio.h>

int main(void) {
    
  //integer variables
  int num = 10;
  int score = 12;
  int run = 123;
  int goal = 3;
  
  //array of integer pointers
  int *ptr[4];
  
  //assign address of variables to ptr
  ptr[0] = &num;
  ptr[1] = &score;
  ptr[2] = &run;
  ptr[3] = &goal;
  
  //print value
  printf("num: %d\n", *ptr[0]);
  printf("score: %d\n", *ptr[1]);
  printf("run: %d\n", *ptr[2]);
  printf("goal: %d\n", *ptr[3]);
  
  return 0;
}
num: 10
score: 12
run: 123
goal: 3
Created Time:2017-08-22 15:17:51  Author:lautturi