This may be because I’m new to C programming, but if I recall my lecturer correctly
PART 1)
execvp(2) takes 2 arguments (obv), the first being the command, and the second being an array of strings such as
char *args[] = {"ls", "-l", "-a", NULL};
Can I please have an explanation of how char *args[] would make this an array of strings rather than an array with chars in it (a C null terminated string)?
PART 2)
How can I make it so that I can add to this array string by string? Could I possibly do
int i;
char *args[255];
for(i = 0; i < strlen(lol); i++)
{
args[i] = //new string being passed in at runtime
}
and would it work like that? Say I was breaking up input from stdin and I wanted to put arguments into args[i].
This declaration
char *args[]can be deciphered as “args is an array of pointers to char”.This means that each entry of an array is pointing to some location where one or more
chars are located.When you do a static initialization declaring
args, compiler reserves the space for exactly the number of initializers you have, each having pointer to char type (in your case, there are 4 pointer in the array).For each of the initializing strings a compiler reserves space (typically in read-only data segment) and puts individual characters there with the null being the last character. The array
argscontains the pointers to this locations. Thus, you have a level of indirection there.Regarding 2), you can do that since
argsas an array of pointers (and not a 2D array). However you should assign the correct memory locations where the null-terminated sequences of characters are. But you have to be sure that youargsarray is of an appropriate size. In case one when no size is given during array declaration, compiler allocates enough space only for the supplied initializers and it won’t be possible to change the size later.