C and pointer in a function - changes do not save

前端 未结 1 1350
北恋
北恋 2020-12-12 03:42

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.



        
相关标签:
1条回答
  • 2020-12-12 04:11

    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

    0 讨论(0)
提交回复
热议问题