I have my array of C-Strings declared as:
char *argv[MAXARGS];
MAXARGS basically just tells us how many c strings are in the array for indexing purposes.
I want to pass it to this function below...
int builtin_cmd(char **argv)
but nothing seems to go through, I called the function like this.
char *argv[MAXARGS];
builtin_cmd(argv);
but once i get into the function builtin_cmd
and try to print using
printf("%s\n", argv[0]);
it prints nothing.... but when i do this before calling the function...
char *argv[MAXARGS];
printf("%s\n", argv[0]);
//builtin_cmd(argv);
it will print the first C string in the array of c strings just fine.
My thoughts are that I am passing the structure incorrecly and I would like to know the correct way to pass it to the function.
EDIT:
int builtin_cmd(char **argv);
int main()
{
char *argv[128];
//put 'quit' into argv[0]..
printf("%s\n", argv[0]); //prints 'quit'
builtin_cmd(argv);
}
int builtin_cmd(char **argv)
{
printf("%s\n", argv[0]); //prints nothing
}
The problem is, again, that I cant seem to get argv into the function. It also compiles with no errors or warnings.
You haven't shown how you initialize the array, and that's the crucial part.
#include <stdio.h>
static void builtin_cmd(char **argv)
{
while (*argv != NULL)
printf("%s\n", *argv++);
}
int main(void)
{
char *argv[] = { "abc", "def", "ghi", NULL };
builtin_cmd(argv);
return 0;
}
This code uses a sentinel value, the null pointer, to mark the end of the data. The alternative is to pass the number of strings in the array as a separate argument. When you use int main(int argc, char **argv)
, you actually have both mechanisms in use; argv[argc] == NULL
so there is the count and then sentinel value.
You are trying to pass an array of charecter pointers to an function so your function declratation should be builtin_cmd(char* argv[])
.Here's an sample example to pass array of pointers to an function
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void fill_strings(char *str[], int nstrings)
{
int i;
for ( i=0; i < nstrings; i++)
strcpy(str[i], "hello world");
}
void print_strings(char *str[], int nstrings)
{
int i;
for (i=0; i < nstrings; i++)
printf("string %d: %s\n", i, str[i]);
}
int main(void)
{
char *index[10];
int i;
for(i=0; i<10; i++)
{
index[i] = malloc(20);
}
fill_strings(index, 10);
print_strings(index, 10);
return 0;
}
If you're passing your input on the command line you need to tell the compiler that you're using the parameters that are passed into main from the runtime.
int main(int argc, char **argv)
{
That should allow you to pass "quit" as the first parameter properly. Otherwise, as the others say, how you fill a "C vector" is important.