The application of the two parameters of the main function of C language learning

  • Two parameters of the main function:
int main(int argc, char const *argv[])
{
    
    
    /* code */
    return 0;
}
  • Parameter argc:
  • Indicates the number of parameters entered in the terminal when executing the program, including the name of the executable file ;
  • Parameter argv:
  • 1. Essentially an array of character pointers ;
  • 2. It is used to obtain the string pointed to by each member in the pointer array;
  • 3. When storing, the parameter argv points to the first address of the string passed ;
  • Pseudocode says:
char *argv[] = {
    
    "./可执行文件名","参数1","参数2","参数3",...,"参数n"};
  • Test code:
#include <stdio.h>


int main(int argc, char const *argv[])
{
    
    

    printf("argc = %d\n",argc);

    puts("-------------------------------");


    int i = 0;

    for(i = 0; i < argc; i++){
    
    


        printf("argv[%d] = %s\n",i,argv[i]);

    }
    
    
    
    return 0;
}

  • operation result:
linux@ubuntu:~$ ./a.out zhangsan lisi wangwu zhaoliu
argc = 5
-------------------------------
argv[0] = ./a.out
argv[1] = zhangsan
argv[2] = lisi
argv[3] = wangwu
argv[4] = zhaoliu

Guess you like

Origin blog.csdn.net/qq_41878292/article/details/132549342