C function argument char * vs char []
23,283
Your understanding is correct. The code is fine.
The following, on the other hand, isn't:
void func(char *str)
{
strcpy(str, "Test");
}
int main()
{
char* testStr = "Original";
func(testStr);
}
This attempts to modify a string literal, resulting in undefined behaviour.
As to the question of readability, that's subjective.
Comments
-
Anish Ramaswamy about 4 years
I think this question is an extension of this SO answer. Say I have the following code:
#include <stdio.h> #include <string.h> void func(char *str) { strcpy(str, "Test"); } int main() { char testStr[20] = "Original"; func(testStr); printf("%s\n", testStr); /* Prints "Test" followed by a new-line */ return 0; }
By my understanding, shouldn't
func
expect a pointer to a read-only literal as an argument? Whereas, what is being passed is a copy on the stack of a read-only literal.Even though this yields correct results, is doing this 100% correct? Would it improve readability of code if
func()
acceptedchar []
instead ofchar *
?