修改作为函数传递的字符串文字 [英] Modifying string literal passed in as a function

查看:109
本文介绍了修改作为函数传递的字符串文字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我的程序中有功能

int main(){
   char *name = "New Holland";
   modify(name);
   printf("%s\n",name);
}

调用此功能

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.

我认为我遇到的问题是new_name是本地存储,因此在函数返回后,该变量将不存储

The problem I think that I face is the new_name is local storage, so after the function returns, the variable is not stored

推荐答案

尝试一下:

#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;
}

如果将new_name定义为数组,则它将成为局部变量,而不是上面定义的指向字符串文字的指针.另外,在C语言中,参数是按值传递的,因此您需要将指针传递给要修改的对象.

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.

这篇关于修改作为函数传递的字符串文字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆