void change(char *string){
string = "Hello";
printf("%s", string);
}
int main (void){
char* s = "Hey";
change(s);
printf("%s", s);
return 0;
}
Shouldn't the code above print "Hello", as the parameter passed to the function is a pointer?
CodePudding user response:
pass a char** if you want a reference to a pointer. Then you can change where the pointer in main points to.
CodePudding user response:
There are a few ways to do what you want. The most common are shown below. It might be worth investigating this to understand what's happening:
#include <stdio.h>
#include <string.h>
void
change(char const **string)
{
*string = "Hello";
}
void
change2(char * string, size_t n)
{
strncpy(string, "hello", n - 1);
}
int
main(void)
{
char const *cs = "Hey";
char * s;
char buf1[32] = "ABC";
char buf2[] = "XYZ";
change(&cs);
change2(s = buf1, sizeof buf1);
change2(s = buf2, sizeof buf2);
return 0;
}