Kees de Groot Kees de Groot - 1 month ago 4
C Question

unable to get filename from argv[1] in C

I'm trying to make a program which makes a copy of the file you put in, only then with a reversed filename (eg. input.txt = txt.tupni).
I start my program with

int main(int argc, char **argv) {

When I use
I can see the file name which has been put in. However, when I try to manipulate it I can't get it to work.
char name = argv[1]
doesnt work,
neither does
char name[] = argv[1]

All I want is either a char array or a piece of malloc memory which has all of the characters.


argv is of type char **, so argv[1] is of type char *. So that's the type of the variable you want to assign this to.

char *name = argv[1];

You can't declare name as char [] and initialize it with a char *. Only a string literal may be used for initialization.

If you want to make a copy of the string rather than have another pointer to it, you can use strdup which allocates memory for the copied string and copies it over.

char *name = strdup(argv[1]);

Don't forget to free it when you're done with it.