-1

I have some code intended to be used in a much larger program, It gets user's input and then should write that input to a file, However the data is somehow lost just before/during writing to a file.

#include <stdio.h>
char *input();
void output(char text[1000]);
int main()
{   
    char text[1000]={'\0'}, *textPtr;
    textPtr=text;   
    textPtr=input();
    output(textPtr);
}

char *input()
{
    char text[1000], *textPtr=text;
    textPtr=text;   
    fflush(stdin);//Clears the newline character left by any prevoius scanf statements
    scanf("%[^\n]s",textPtr);
    return textPtr;
}

void output(char text[1000])
{
    FILE *file;
    printf("\nText before file statement:\n");
    printf("%s\n",text);
    //For some reason this line seems to trigger a change in 'text'
    file=fopen("output.txt","a");
    printf("\nText after file statement:\n");
    printf("%s\n",text);    
    fprintf(file,"%s\n",text);
    fclose(file);       
    printf("\nText after write and close statement:\n");
    printf("%s\n",text);    
}

The print statements in the output function output something similar to this image no matter the input

enter image description here

So it prints the desired contents of 'text' directly before those contents are used in the intended way, it then replaces those contents with nothing, and writes just a line break to the text document and then in the next print statement the text becomes a single strange accented character (varies each time program is run).

So I believe somehow I have misused pointers or I am returning the char array from a function in a strange way.

1 Answers1

0

textPtr=input(); return a new pointer on the stack that is freed when the function input return and then this memory (stack) can be use again. To fix this you have to pass textPtr as parameters of input

input(textPtr);//the call

input(char * textPtr){//the function
    fflush(stdin);//Clears the newline character left by any prevoius scanf statements
    scanf("%[^\n]s",textPtr);
}
MrFreezer
  • 1,627
  • 1
  • 10
  • 8