Occasionally interested in the parameters of the main function, write a program for verification.
Int main (int argc, char ** argv)
First, two points are explained:
First, the system will store the parameter list, that is, the command we input under shell, to a one-dimensional character array, and the user can be modified, there must be no constant area.
2. argv is actually a char * argv [], character pointer array. The number of elements is unclear. There are at least argc elements, and some others, such as HOSTNAME, SELINUX_ROLE_REQUESTED, TERM, SHELL, HISTSIZE, SSH_CLIENT, SELINUX_USE_CURRENT_RANGE, QTDIR, QTINC, SSH_TTY, SVN_EDITOR, etc,
Then, based on the space in the parameter list, divide the parameters, store the first address of each parameter to argv [I], and set * (argv [I]-1) to 0, use \ 0 instead of the original space to print the parameters.
The following shows my program. You can test it on your own.
/* Argcargv. c */
# Include <stdio. h>
# Include <string. h>
Int main (int argc, char ** argv)
{
Int I;
For (I = 0; I <argc/* 20, you can set a value greater than argc to see how many elements argv has */; I ++)
{
Printf ("% p, % s", argv [I], argv [I]);
Printf ("$ \ n ");
}
Printf ("\ n ");
Strcpy (argv [0], "meilidezhongguo, nihao! ");
For (I = 0; I <argc, I ++)
{
Printf ("% p, % s", argv [I], argv [I]);
Printf ("$ \ n ");
}
Printf ("\ n ");
}
Program running:./a. out abc 123 def 456 hello 789 world
My computer runs as follows:
0xbff64758,./a. out $
0xbff64760, abc $
0xbff64764, 123 $
0xbff64768, def $
0 x bff6476c, 456 $
0xbff64770, hello $
0xbff64776, 789 $
0xbff6477a, world $
(Nil), (null) $
.......
.......
.......
.......
0xbff64758, meilidezhongguo, nihao! $
0xbff64760, hongguo, nihao! $
0xbff64764, guo, nihao! $
0xbff64768, nihao! $
0xbff6476c, o! $
0xbff64770, hello $
0xbff64776, 789 $
0xbff6477a, world $
You can also use
Strncpy (argv [0], "meilidezhongguo, nihao! ", 28 );
Replace strcpy (argv [0], "meilidezhongguo, nihao! ");
Try,
We can also see that strncpy has copied 22 characters, strlen ("meilidezhongguo, nihao! "); Add \ 0 to the remaining six characters.
Understanding restrictions can only be added. Next time, you will have a new understanding and improvement!