【发布时间】:2018-05-06 20:59:04
【问题描述】:
我试图通过将字符串的指针传递给函数,然后在函数中更改该指针的值来更改字符串 t_string 的值。
我收到的输出是原始字符串“Hello”。
任何帮助将不胜感激:) 谢谢!
#include <stdio.h>
#include "string.h"
void editString(char *theString);
int main() {
char t_string[] = "Hello\n";
char *s = t_string;
editString(s);
printf("The string after: %s", t_string);
return 0;
}
void editString(char *theString){
theString = "Good Bye\n";
}
【问题讨论】:
-
您需要传递指针的地址而不是
void editString(char **theString) { *thString = "Good Bye\n" },但请注意,生成的字符串将指向字符串文字,而最初它指向的是数组。 -
'theString = "再见\n";'更改函数参数,但不更改调用者的参数。 C函数参数按值传递,即。它们被复制到参数中。
-
@IharobAlAsimi:使用你的代码可能会导致核心转储,因为最后几个字节没有正确分配,对吧?
-
@LionLai 不,因为重新分配指针不是问题。
标签: c string function pointers