Whenever I compile my c program, I get this error for both of my argv[]'s. error: invalid initializer char baseDir[] = argv[0]; error: invalid initializer char pattern[] = argv[1];
This is a snippet of the main method in my program.
void walkDir(char *baseddir, char *pattern);
int main(int argc, char *argv[]){
char baseDir[] = argv[0];
char pattern[] = argv[1];
walkDir(baseDir, pattern);
if(count==0){
printf("No match found \n");
}
printf("\n Done \n");
return 0;
}
CodePudding user response:
argv[0]
and argv[1]
are char*
. They point at strings of unknown length. argv[0]
usually holds a pointer to the name of the program itself while argv[1]
holds a pointer to the first argument supplied to the program.
To initialize a char[]
you need something like this:
char baseDir[] = "a string literal";
In your case, it's not a string literal so you can't initialize a char[]
with it, so you probably should just copy the pointers:
const char *baseDir = argv[1]; // a pointer to the first argument
const char *pattern = argv[2]; // a pointer to the second argument
I added const
since you shouldn't change the strings they are pointing at. I suppose you are not planning to change the strings in your walkDir
function either, so then change it accordingly:
void walkDir(const char *baseddir, const char *pattern)