Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modifying string literal passed in as a function

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

like image 277
painterofthewind Avatar asked Jan 15 '23 03:01

painterofthewind


2 Answers

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.

like image 151
perreal Avatar answered Jan 20 '23 06:01

perreal


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.

like image 43
sharingli Avatar answered Jan 20 '23 07:01

sharingli