C和指针的函数 - 更改不保存 [英] C and pointer in a function - changes do not save
问题描述
我有这个简单的code,似乎工作(我与调试检查),但是当函数执行结束,该字符串不会被保存在原来的变量。
I have this simple code that seems to work (I checked with the debugger) but when the function execution ends, the string is not saved in the original variable.
void getString(char *iText);
int main()
{
char *inputText=malloc(sizeof(char));
getString(inputText);
puts(inputText);
free(inputText);
system("pause");
return 0;
}
void getString(char *iText)
{
char c;
int i=0;
while((c=getchar()) != '\n')
{
iText = realloc(iText,sizeof(char)*(i+1));
iText[i]=c;
i++;
}
iText = realloc(iText, sizeof(char)*(i+1));
iText[i]='\0';
}
在这个脚本结束后,我看到一些
When this little script ends, I see some
ε■ε■ε■ε■ε■ε■ε■ε■ε■ε■ε■ε■▲יע`*
ε■ε■ε■ε■ε■ε■ε■ε■ε■ε■ε■ε■▲יע`*
如果我写在它的工作我的主要功能这个code,所以我猜它是与我使用的指针在函数的方式。
If I write this code in my main function it's working, so I'm guessing it's something to do with the way I'm using the pointer in the function.
推荐答案
的getString
按值需要一个指针所以不能改变调用者的指针。传递一个指针的指针,如果你想重新分配字符串
getString
takes a pointer by value so cannot change the caller's pointer. Pass a pointer to a pointer if you want to reallocate the string
int main()
{
....
getString(&inputText);
....
}
void getString(char **iText)
{
char c;
int i=0;
while((c=getchar()) != '\n')
{
*iText = realloc(*iText, i+1);
(*iText)[i]=c;
i++;
}
*iText = realloc(*iText, i+1);
(*iText)[i]='\0';
}
我已经做了一个其他的小变化到你的code - 的sizeof(char)的
保证是1,因此 realloc的
的计算可以简化
I've made one other small change to your code - sizeof(char)
is guaranteed to be 1 so the realloc
calculations can be simplified
这篇关于C和指针的函数 - 更改不保存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!