I have a function
ValArgument(char* ptr){
char str[] = "hello world";
ptr = &str[0];
}
In this function, I want to init a char array and add it to the char pointer ptr. I call the function like that:
char* ptr= NULL;
ValArgument(ptr);
The pointer returned still has the value NULL. Why? I expected that the pointer will point onto the char array str[].
Because you passed the pointer by value. That means that the function is given a separate copy of the pointer, and any changes it makes to the pointer will not affect the caller’s copy.
You can either pass by reference:
or return a value:
No; once you’ve fixed that problem, it will point to the undead husk of the local variable that was destroyed when the function returned. Any attempt to use the pointer will cause undefined behaviour.
Depending on what you need to do with the string, you might want:
char const * str = "hello world";. Note that this should beconst, since string literals can’t be modified.static char str[] = "hello world";. This means that there is only one string shared by everyone, so any modification will affect everyone.std::string str = "hello world";. This is the least error-prone, since it can be passed around like a simple value.