作为函数参数的char *args[]与char **argv有何区别?是否等价?
char *args[]与char **argv的等价性解析 Great question! Let's cut through the confusion here—you're absolutely right to question the common explanations floating around.
First, let's address the core point: when used as function parameters, char *argv[] and char **argv are completely equivalent. The popular claim that "char *argv[] is an array of pointers, char **argv is a pointer to a pointer" is only true for variable declarations outside function parameters. Inside a function's parameter list, array types undergo what's called "array decay"—the compiler automatically converts the array type to a pointer to its first element.
So when you write:
int main(int argc, char *argv[]) { ... }
The compiler treats argv exactly the same as if you had written:
int main(int argc, char **argv) { ... }
Your observation about being able to use argv as an lvalue (on the left side of an assignment) is perfect proof of this. A true array variable cannot be assigned to—try this in main, and you'll get a compiler error:
int main() { char *real_array[] = {"a", "b", NULL}; char *another_array[] = {"x", "y", NULL}; real_array = another_array; // ❌ Compile error: array type is not assignable return 0; }
But do the same inside a function where argv is declared as char *argv[], and it works perfectly:
void process_args(char *argv[]) { char *new_args[] = {"hello", "world", NULL}; argv = new_args; // ✅ Totally legal—argv is a char** pointer here printf("%s\n", argv[0]); // Outputs "hello" }
Why does this happen? Because function parameters can't be arrays. The syntax char *argv[] is just syntactic sugar that makes the code more readable (it hints that we're dealing with an array of strings), but under the hood, it's a pointer to a pointer.
To sum up:
- For variable declarations (not function parameters),
char *arr[]is an array of pointers, andchar **ptris a pointer to a pointer—these are distinct types. - For function parameters,
char *argv[]is converted tochar **argvby the compiler. They are identical in behavior, memory representation, and what you can do with them.
内容的提问来源于stack exchange,提问作者ynn

