You can treat argv[1]
as though it were an array of char
(i.e., you can subscript it as argv[1][i]
). You can pass it as an argument to any function that doesn't try to modify it (e.g., printf
, strtol
, strchr
, etc.). You cannot write to it, though, so if you need to modify the contents for any reason (either directly or through a function like strtok
or strcpy
), you'll have to create a local copy and manipulate that.
If you are using C89 or earlier, use this method:
#include <stdlib.h>
#include <string.h>
int main(int argc, char **argv)
{
char *c = NULL;
if (argc >= 2)
{
c = malloc(strlen(argv[1]) + 1);
strcpy(c, argv[1]);
}
/**
* Do stuff with c
*/
free(c);
return 0;
}
If you are using C99, you can use a VLA:
#include <string.h>
int main(int argc, char **argv)
{
if (argc < 2)
return 0;
size_t len = strlen(argv[1]);
char c[len+1];
strcpy(c, argv[1]);
/**
* do stuff with c
*/
return 0;
}
Just remember a few things:
The type of argv
is char **
, not char *[N]
; similarly, the type of argv[i]
is char *
, not char [M]
. In most circumstances it doesn't matter; you can use a subscript operator on a pointer as though it were an array (array subscripting is defined in terms of pointer arithmetic), but remember that pointers and arrays are not the same thing and are not always interchangeable;
The value of argv[argc]
is always NULL
;
Except when it is the operand of the sizeof
or unary &
operators or is a string literal being used as an initializer in a declaration, an expression of array type is converted ("decays") from "N-element array of T" to "pointer to T", and the value of the expression is the location of the first element;
C doesn't have a string data type as such; strings are represented as 0-terminated sequences of char
. String literals such as "hello"
are stored in such a way that they exist over the lifetime of the program, and you can access them via a pointer value; attempting to modify them results in undefined behavior (i.e., don't do that).