I was making some function that takes string as function argument but
// This is working fine
char string[] = "Any string";
func(string);
//This is not working
func("Any string");
Please tell me the difference
I was making some function that takes string as function argument but
// This is working fine
char string[] = "Any string";
func(string);
//This is not working
func("Any string");
Please tell me the difference
What is the difference in using variable as function argument and in using directly string as function argument?
char string[] = "Any string";
func(string);
// VS.
func("Any string");
string[]
is a character array initialized with the size and contents of "Any string"
.
"Any string"
is a string literal.
If func()
is func(const char *s)
, then no difference as func()
simply is reading the string.
If func()
is func(char *s)
, yet does not modify the string pointed to by s
, then then no difference as func()
simply is reading the string.
If func()
is func(char *s)
, and attempts to modify the string pointed to by s
OP later reports this, then func(string)
is OK as string
is a modifiable character array. Yet func("Any string")
is undefined behavior (UB). @John3136 @William Pursell Code should not attempt to modify a string literal. As OP reports the first works and the 2nd is "not working", this is the prime suspect.
For certainty, the definition of func()
is needed as other explanations are possible.
As per your description, it seems that the prototype of your function
func(char* str);
OR
func(char str[]);
Now the problem comes in the datatype of the String. When you func("Any string");
which is expecting a pointer value (as an Array also works as a pointer) you are giving it a string value which will definitely generate an error as the arguments are miss-matched.
If you still want to pass a string use this:
str = "Any String";
func(str.toCharArray());
ok, so.... When you declare a "text string", it's type is:
const char* const text = "text string";
Now you can copy that to a char buffer, so this is ok:
char string[] = "Any string";
because 'string' in this context is a copy of the original text (with it's own memory). This however would not be ok:
char* ptr = "Some Text";
The reason is that "Some Text" is constant, and you are asking to refer to it as some memory that can be changed. This would imply to me that your 'func' has the following prototype:
void func(char* str);
Now in the above example, you could pass 'string' to it because the types match. You can't pass "Any String" though, because it's const. If however the prototype is:
void func(const char* str);
Then there should be no issue.