Hi, the question I am about to ask is a part of bigger home work task. However I am stuck at this and do not know how to proceed further. My task is to receive input from the user, the input is arbitrary number of strings ending, with '\0' character. Once I am done with inputing strings I should save them (this part I think I am done with). The next part is to split up saved input in to separate strings, the splitting should be done whenever I encounter new line character '\n'.
Right now all I want is to out put fragmented strings. Unfortunately code works in a way that I can not understand. Lets say input is following:
Code:
First line of text 1
Second line of text 2
Third line of text 3
Running program with the input above, outputs following:
Code:
Firs
Second Q te of text 2
Third line of text 3
�
Segmentation fault
Code of the program is
Code:
#include <stdio.h>
#include <stdlib.h>
char *ReadInput(void);
void Divide (char text[]);
int main(void) {
char *textReceived;
textReceived=ReadInput();
Divide(textReceived);
return 0;
}
void Divide (char text[]) {
char *tmpString=NULL;
int i=0, j=0;
tmpString=(char *)malloc(sizeof(char));
while ((text[i])!='\0') {
if ((tmpString[j])=='\n') {
printf("%s\n", tmpString);
tmpString=NULL;
j=0;
i++;
}
else
tmpString[j++]=text[i++];
}
}
char *ReadInput(void) {
char *string;
int i=0;
string=(char *)malloc(sizeof(char));
while ((string[i++]=getchar())!=EOF)
;
return string;
}
I do not understand what is wrong with the code, please help.
Regards,
Alex