Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
902 views
in Technique[技术] by (71.8m points)

arrays - C and pointer in a function - changes do not save

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

ε■ε■ε■ε■ε■ε■ε■ε■ε■ε■ε■ε■▲??`*

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...