C and pointer in a function - changes do not save

2019-01-20 16:00发布

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

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

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.

1条回答
冷血范
2楼-- · 2019-01-20 16:37

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

I've made one other small change to your code - sizeof(char) is guaranteed to be 1 so the realloc calculations can be simplified

查看更多
登录 后发表回答