Cprogramming 简明教程

Initialization of Pointer Arrays in C

pointer 是一个变量,可存储另一个变量的地址。指针变量的名称必须带有前缀“*”符号。正如普通变量一样,我们还可以声明“指针数组”,其中数组的每个下标都保存数组类型的地址。

A pointer is a variable that stores the address of another variable. The name of the pointer variable must be prefixed by the "*" symbol. Just as in the case of a normal variable, we can also declare an "array of pointers", where each subscript of the array holds the address of an array type.

How to Initialize Array of Pointers in C?

指针变量可以在声明时通过给它分配现有变量的地址来初始化。以下片段显示如何初始化指针 −

A pointer variable can be initialized at the time of declaration, by assigning it the address of an existing variable. The following snippet shows how you can initialize a pointer −

int x = 10;
int *y = &x;

默认情况下,所有 variables (包括指针变量)都属于“auto 存储类”。这意味着指针变量将存储不可预测的垃圾、随机内存地址,这可能导致未定义的行为以及程序的潜在风险,例如段错误。因此,如果我们在声明时没有特定的值要存储,则应将其初始化为 NULL。

By default, all the variables including the pointer variables belong to the "auto storage class". It means that a pointer variable will store an unpredictable, garbage, random memory address, which can lead to undefined behavior and potential risks to a program, such as segmentation fault errors. Hence, it should be initialized to NULL if we don’t have a specific value to store at the time of declaration.

int *ptr = NULL;

“指针数组”存储每个元素中的地址。数组的类型必须与目标变量的类型匹配。

A "pointer array" stores the address in each element. The type of the array must match with the type of the target variable.

Initialize Array of Pointers Using static Keyword

您还可以使用 static keyword 来初始化一个 array of pointers ,在每个下标中存储“0”。

You can also use the static keyword to initialize an array of pointers to store "0" in each subscript.

Example

#include <stdio.h>

int main(){

   static int *ptr[5];

   for (int i = 0; i < 5; i++){
      printf("ptr[%d] = %d\n", i, ptr[i]);
   }

   return 0;
}

运行代码并检查其输出:

Run the code and check its output −

ptr[0]= 0
ptr[1]= 0
ptr[2]= 0
ptr[3]= 0
ptr[4]= 0

Initialize Array of Integer Pointers

在此,我们声明一个整数指针数组,并存储三个整数变量的地址。

Here, we declare an array of integer pointers and store the addresses of three integer variables.

Example

#include <stdio.h>

int main(){

   int a = 10, b = 20, c = 30;
   int *ptr[3] = {&a, &b, &c};

   for (int i = 0; i < 3; i++){
      printf("ptr[%d]: address: %d value: %d\n", i, ptr[i], *ptr[i]);
   }

   return 0;
}

运行代码并检查其输出:

Run the code and check its output −

ptr[0]: address: 6422040 value: 10
ptr[1]: address: 6422036 value: 20
ptr[2]: address: 6422032 value: 30

Initialize Array of Pointer by Direct Addresses

我们可以将普通数组中每个元素的地址存储在指针数组的相应元素中。

We can store the address of each element of a normal array in the corresponding element of a pointer array.

Example

#include <stdio.h>

int main(){

   int arr[] = {10, 20, 30};
   int *ptr[3] = {&arr[0], &arr[1], &arr[2]};

   for (int i = 0; i < 3; i++){
      printf("ptr[%d]: address: %d value: %d\n", i, ptr[i], *ptr[i]);
   }

   return 0;
}

运行代码并检查其输出:

Run the code and check its output −

ptr[0]: address: 6422032 value: 10
ptr[1]: address: 6422036 value: 20
ptr[2]: address: 6422040 value: 30

Traversing an Array with its Base Address

当我们获得数组的基址(在本例中为“&arr[0]”)时,我们可以获得其后续元素的地址,知道指针会以数据类型的大小递增。

When we obtain the base address of an array (in this case "&arr[0]"), we can obtain the addresses of its subsequent elements, knowing that the pointer increments by the size of the data type.

因此,只需使用基地址(数组的名称与第 0 个元素的地址相同),我们就可以遍历数组。

Hence, just with the base address (the name of the array is the same of the address of the 0th element), we can traverse an array.

Example 1

请看以下示例:

Take a look at the following example −

#include <stdio.h>

int main(){

   int arr[] = {10, 20, 30};
   int *ptr=arr;

   for (int i = 0; i < 3; i++){
      printf("ptr[%d]: address: %d value: %d\n", i,ptr+i, *(ptr+i));
   }

   return 0;
}

运行代码并检查其输出:

Run the code and check its output −

ptr[0]: address: 6422020 value: 10
ptr[1]: address: 6422024 value: 20
ptr[2]: address: 6422028 value: 30

Example 2: Traversing a 2D Array using a Pointer Array

在此示例中,我们有一个 2D array 。每行的第 0 个元素的地址存储在指针数组中。遍历时,存储在指针数组的每个元素中的地址指向相应行的第 0 个元素,每个元素都会递增以获取每行中的值。

In this example, we have a 2D array. The address of the 0th element of each row is stored in a pointer array. When traversing, the address stored in each element of the pointer array, that points to the 0th element of the corresponding row, each incremented to fetch the values in each row.

#include <stdio.h>

int main(){

   // 2d array
   int arr[3][4] = {
      {1, 2, 3, 4},
      {5, 6, 7, 8},
   };

   int ROWS = 2, COLS = 4;
   int i, j;

   // pointer
   int (*ptr)[4] = arr;

   // print the element of the array via pointer ptr
   for (i = 0; i < ROWS; i++) {
      for (j = 0; j < COLS; j++) {
         printf("%d ", *(ptr[i]+j));
      }
      printf("\n");
   }

   return 0;
}

当你运行这段代码时,它将产生以下输出:

When you run this code, it will produce the following output −

1 2 3 4
5 6 7 8

Example 3

我们这里实际上并不需要指针数组,因为我们可以将此 2D 数组的名称用作它的基指针,并按行和按列递增它来获取给定 2D 数组中的元素 −

We don’t really need a pointer array here, as we can use the name of this 2D array as its base pointer, and increment it row and column-wise to fetch the elements in the given 2D array −

#include <stdio.h>

int main(){

   // 2d array
   int arr[3][4] = {
      {1, 2, 3, 4},
      {5, 6, 7, 8},
   };

   int ROWS = 2, COLS = 4;
   int i, j;

   // pointer
   int *ptr = arr;

   // print the element of the array via pointer ptr
   for (i = 0; i < ROWS; i++){
      for (j = 0; j < COLS; j++){
         printf("%d  ", *(ptr + i * COLS + j));
      }
      printf("\n");
   }

   return 0;
}

输出类似于上一段代码 −

The output resembles that of the previous code −

1  2  3  4
5  6  7  8

Initialize Array of Character Pointers (String)

在 C 编程中,字符串是一个 char 数据类型数组。由于数组的名称也表示其第 0 个元素的地址,因此可以将字符串声明为 −

In C programming, a string is an array of char data type. Since the name of an array also represents the address of its 0th element, a string can be declared as −

char arr[] = "Hello";

使用指针表示法,将字符串分配给 char 指针,如下所示 −

Using the pointer notation, a string is assigned to a char pointer as −

char *arr = "Hello";

然后我们可以声明一个 char 指针数组以存储多个 strings ,如下所示 −

We can then declare an array of char pointers to store multiple strings as follows −

char *arr[3] = {"string1", "string2", "string3", . . . };

Example

以下示例有一个 char pointers 数组,用于存储计算机语言的名称 −

The following example has an array of char pointers that is used to store the names of computer languages −

#include <stdio.h>

int main(){

   char *langs [10] = {
      "PYTHON", "JAVASCRIPT", "PHP",
      "NODE JS", "HTML", "KOTLIN", "C++",
      "REACT JS", "RUST", "VBSCRIPT"
   };

   for(int i = 0; i < 10; i++)
      printf("%s\n", langs[i]);

   return 0;
}

当你运行这段代码时,它将产生以下输出:

When you run this code, it will produce the following output −

PYTHON
JAVASCRIPT
PHP
NODE JS
HTML
KOTLIN
C++
REACT JS
RUST
VBSCRIPT

在此程序中,“ langs ”是一个包含 10 个字符串的 pointer to an array 。因此,如果“langs[0]”指向地址 5000,则“langs + 1”将指向地址 5004,该地址存储指向第二个字符串的指针。

In this program, "langs" is a pointer to an array of 10 strings. Therefore, if "langs[0]" points to the address 5000, then "langs + 1" will point to the address 5004 which stores the pointer to the second string.

因此,我们还可以使用以下循环变体来打印字符串数组 −

Hence, we can also use the following variation of the loop to print the array of strings −

for (int i = 0; i < 10; i++){
   printf("%s\n", *(langs + i));
}

Initialization of Dynamic Array of Pointers

你可以使用 malloc() function 以动态方式声明和初始化一个指针数组。

You can use the malloc() function to declare and initialize an array of pointers in a dynamic way.

Example

请看以下示例:

Take a look at the following example −

#include <stdio.h>

int main(){

   int *arr = (int *)malloc (sizeof (int) * 5);

   for(int i = 0; i < 5; i++){
      arr[i] = i;
   }
   for (int x = 0; x < 5; x++){
      printf("%d %d\n", x, arr[x]);
   }

   return 0;
}

当你运行这段代码时,它将产生以下输出:

When you run this code, it will produce the following output −

0 0
1 1
2 2
3 3
4 4

您甚至可以要求 user input 并将值分配给指针数组中的元素 −

You can even ask for user input and assign the values to the elements in the pointer of arrays −

for(i = 0; i < 5; i++){
   scanf("%d", &x);
   arr[i] = x;
}