C语言函数返回字符串时数组赋值报错问题求助
Hey there! Let's clear up this confusion step by step.
a=myFunction(); Throws an Error In C, array types are not assignable. When you declare char a[101];, the identifier a acts as an immutable lvalue—it's a fixed reference to the array's memory location, and you can't reassign it to point somewhere else (unlike a pointer variable).
Your myFunction() returns a const char* (a pointer to the first element of the static array), but trying to assign this pointer directly to the array a breaks C's rules: you can't overwrite the array's base address with the = operator.
printf("%s", myFunction()); Works The printf function's %s format specifier expects a const char* argument (a pointer to a null-terminated string). When you pass myFunction() directly to printf, you're giving it exactly the pointer type it needs.
Even if you passed a directly to printf (like printf("%s", a);), it would work too—because in most contexts, an array name is implicitly converted to a pointer to its first element. But this implicit conversion doesn't make arrays assignable.
You have two reliable options here:
1. Copy the string into the array
Use a string-copying function like strcpy (or strncpy for safer bounds checking) to copy the characters from the returned pointer into your array:
#include <string.h> // Required for strcpy/strncpy const char* myFunction() { static char array[] = "my string"; return array; } int main() { char a[101]; strcpy(a, myFunction()); // Copies the static string into array a // For safer buffer overflow prevention: // strncpy(a, myFunction(), sizeof(a)-1); // a[sizeof(a)-1] = '\0'; // Ensure the string is null-terminated printf("%s\n", a); return 0; }
2. Declare a as a pointer instead of an array
If you don't need a separate copy of the string and just want to reference the static version, change a to a pointer:
const char* myFunction() { static char array[] = "my string"; return array; } int main() { const char* a; // Match the const qualifier from the function's return type a = myFunction(); // This assignment is now valid printf("%s\n", a); return 0; }
Since array is declared static, its memory persists for the entire program's lifetime—so the pointer returned by myFunction() will never become a dangling pointer.
内容的提问来源于stack exchange,提问作者Mahdi Hosseini

