Pointer array as formal parameter of main function

Table of contents

Edit

1. Pointer array

1.1 Basic concepts

1.2 Simple example

2. Pointer array as main parameter

2.1 int main(int argc, char *argv[]);

2.2 Simple example


1. Pointer array

1.1 Basic concepts

An array of pointers is an array in which each element is a pointer.

This means that each element in the array stores an address that points to a location in memory.

The declaration form of an array of pointers is:

data_type *array_name[size];

//示例:
int *p[10];//该指针数组包含10个整型地址

1.2 Simple example

Here is a simple example that demonstrates how to declare and use an array of pointers:

#include <stdio.h>

int main() {
    // 声明一个整型数组
    int num1 = 10, num2 = 20, num3 = 30;
    int *intArray[3]; // 声明一个包含3个整型指针的数组

    // 将指针指向整型变量
    intArray[0] = &num1;
    intArray[1] = &num2;
    intArray[2] = &num3;

    // 访问指针数组中的元素并输出值
    for (int i = 0; i < 3; i++) {
        printf("Value at index %d: %d\n", i, *intArray[i]);
    }

    return 0;
}
/*输出结果:
Value at index 0: 10
Value at index 1: 20
Value at index 2: 30
*/

2. Pointer array as main parameter

2.1 int main(int argc, char *argv[]);

An important application of pointer array is as a formal parameter of the main function.

1. mainThe prototype of a function is usually defined as

int main(int argc, char *argv[]);

illustrate:

  1. Among them, argcrepresents the number of command line parameters, argvwhich is an array of pointers, each element is a pointer to a null-terminated string.
  2. If the main function takes parameters, the first parameter must be of int type , and the second parameter must be a character pointer array char *xx[] . The parameters can only be given by the operating system.

2.2 Simple example

In the following example, argcrepresents the number of command line parameters, but argvis an array of pointers, where each element is a pointer to a string. The program loops through argvthe array and outputs the contents of each command line parameter.

#include <stdio.h>

int main(int argc, char *argv[]) {
    printf("Number of command line arguments: %d\n", argc);

    // 遍历指针数组,输出每个命令行参数
    for (int i = 0; i < argc; i++) {
        printf("Argument %d: %s\n", i, argv[i]);
    }

    return 0;
}
/*输出
Number of command line arguments: 1
Argument 0: D:\Program Files\code\CC++程序集合\c\【谭浩强】C语言自学\output\mytest.exe
*/

Guess you like

Origin blog.csdn.net/m0_57532432/article/details/135410701