If I have a function in program
int main(){
char *name = "New Holland";
modify(name);
printf("%s\n",name);
}
that calls this function
void modify(char *s){
char new_name[10] = "Australia";
s = new_name; /* How do I correct this? */
}
how can I update the value of the string literal name (which now equals new Holland) with Australia.
The problem I think that I face is the new_name is local storage, so after the function returns, the variable is not stored
Try this:
#include <stdio.h>
void modify(char **s){
char *new_name = "Australia";
*s = new_name;
}
int main(){
char *name = "New Holland";
modify(&name);
printf("%s\n", name);
return 0;
}
If you define new_name
as an array then it will become a local variable, instead the above defines a pointer, to a string literal. Also, in C the parameters are passed by value, so you need to pass pointers to objects you want to modify.
Try this:
#include <stdio.h>
#include <string.h>
#define MAX_NAME_LEN 50
void modify(char *mdf){
char *new_name = "Australia";
strcpy(mdf,new_name);
}
int main(){
char name[MAX_NAME_LEN] = "New Holland";
modify(name);
printf("%s\n", name);
return 0;
}
use strcpy/memcpy to bing a local array variable to an outer string literal.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With