I am using a simple main like this
#include <string.h>
int main(int argc, char **argv)
{
char buf[256];
strcpy(buf, argv[1]);
}
I understand that if compiled, this main will produce 'argc' with a value of one, and argv[1] would not exist as defined in this program. However, the memory address represented by argv[1], although not defined in this program, would not be modified by the program, as argv[1] is passed as a const char *. So my question is why strcpy cannot grab this char and write it into buf? Also, why is argc = 1?
Q:So my question is why strcpy cannot grab this {argv[1]} char and write it into buf?
You can. The only problems you might encounter is if argc
is less than 2, or if argv[1] is larger than 255 bytes (plus the string termination character).
Q:Also, why is argc = 1?
On most systems, the lay-out of the argv[] array has the same layout. For example, assume that a program was executed from the command-line:
>./myprog cookie monster
argv[0] Contains the path where the executing program resides in the filesystem.
So the actual value is something like: '/home/mahonri/test/test'
This value is provided by the operating system.
argv[1] Will contain the string: 'cookie'
This value is provided (optionally) by the user.
argv[2] will contain the string: 'monster'
This value is provided (optionally) by the user.
argc will be '3', because there are three argv elements; 0, 1 and 2.
In the case of the question code, if argc is '1', then only argv[0] is initialized; and unpredictable things will happen if the code then attempts to access argv[1] or argv[2].