函数中的 C 和指针 - 更改不保存 [英] C and pointer in a function - changes do not save

查看:12
本文介绍了函数中的 C 和指针 - 更改不保存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个似乎可以工作的简单代码(我用调试器检查过)但是当函数执行结束时,字符串没有保存在原始变量中.

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()) != '
')
    {
        iText = realloc(iText,sizeof(char)*(i+1));
        iText[i]=c;
        i++;
    }

    iText = realloc(iText, sizeof(char)*(i+1));  
    iText[i]='';
}

当这个小脚本结束时,我看到了一些

When this little script ends, I see some

ε■ε■ε■ε■ε■ε■ε■ε■ε■ε■ε■ε■▲יע`*

ε■ε■ε■ε■ε■ε■ε■ε■ε■ε■ε■ε■▲יע`*

如果我在 main 函数中编写这段代码,它就可以工作,所以我猜这与我在函数中使用指针的方式有关.

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()) != '
')
    {
        *iText = realloc(*iText, i+1);
        (*iText)[i]=c;
        i++;
    }

    *iText = realloc(*iText, i+1);  
    (*iText)[i]='';
}

我对您的代码进行了另一项小改动 - 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屋!

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