为何C语言中用argv[1]初始化char数组会触发编译错误?
Great question—this trips up a lot of folks learning C, so let's break it down clearly.
First, why char s[32] = "A test string"; works
When you use a string literal (like "A test string") to initialize a char array, C's standard explicitly allows this as a special case. The string literal is a compile-time constant—the compiler knows its full content before your program even runs. It automatically copies every character (including the hidden \0 terminator) into the array s during the initialization phase (either at compile time for static arrays, or right when the local array is created on the stack).
So why doesn't char s[32] = argv[1]; work?
argv[1] is a char* pointer—it points to memory holding the first command-line argument, but this memory only exists when your program is running. Here's the key reasons the compiler rejects this:
- C's array initialization rules only allow two valid options for char arrays: an initializer list (like
{'h','i','\0'}) or a string literal. A runtime pointer likeargv[1]doesn't fit either category. - Initialization happens before your program's main logic executes. The compiler can't possibly know what
argv[1]will be when you compile the code, so it can't copy its contents into the array during initialization.
The correct approach
You need to copy the contents of argv[1] into your array at runtime using a string manipulation function. Always remember to check if the argument exists first (to avoid crashing on a null pointer) and use a safe copy function to prevent buffer overflows:
#include <stdio.h> #include <string.h> int main(int argc, char** argv) { // First, verify the user provided an argument if (argc < 2) { printf("Please pass a command-line argument!\n"); return 1; } char s[32]; // Use strncpy to safely copy up to 31 characters (leave space for the null terminator) strncpy(s, argv[1], sizeof(s) - 1); // Manually add the null terminator in case argv[1] is longer than 31 characters s[sizeof(s) - 1] = '\0'; printf("entered char is %s\n", s); }
One extra note: You also can't do char s[32]; s = argv[1]; later in the code either—array names are immutable in C, so you can't assign to them directly. Copying is the only way to get the string content into the array.
内容的提问来源于stack exchange,提问作者cs276

