Modifying string literal passed in as a function

时间秒杀一切 提交于 2019-12-31 05:29:06

问题


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


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/14992772/modifying-string-literal-passed-in-as-a-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!