在其他函数中使用malloc更改字符串 [英] Change string with malloc in other function
本文介绍了在其他函数中使用malloc更改字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
使用malloc时如何更改其他函数中的字符串?
how can I change string in other function when I am using malloc?
in main:
char *myString;
changeString(myString);
changeString(char *myString){
myString = malloc((size) * sizeof(char));
myString[1] = 'a';
}
谢谢
推荐答案
C中的参数按值传递.因此,要在函数中修改变量,您必须将指针传递给它.例如,int *
到int
,char **
到char *
.
Parameters in C are passed by value. So to modify a variable within a function, you'll have to pass the pointer to it. For example, int *
to int
, and char **
to char *
.
void changeString(char **myString){
// free(*myString); // add when myString is allocated using malloc()
*myString = malloc(2);
(*myString)[0] = 'a';
(*myString)[1] = '\0';
}
这篇关于在其他函数中使用malloc更改字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文