-2
typedef struct {
    char *inputString;
    int stringLenght;
} InputString;



string = (InputString *) malloc(NUMOFSTRING * sizeof(InputString));
string->inputString = (char *)malloc(STRINGLENGHT);
currentString = 1;
scanf("%c", &e);
while (e == ' ' || e == '\n') {
      scanf("%c", &e);
}
while (!feof(stdin)) {
   currentStringLenght = 1;
   while (e != '\n' && e != ' ') {
    string->inputString = &e;
    currentStringLenght++;
    if (currentStringLenght > STRINGLENGHT) {
     string->inputString = (char*) realloc(string->inputString, currentStringLenght);
    string->inputString = string->inputString + (currentStringLenght - 1);
    } else {
     string->inputString ++;
     scanf("%c", &e);
    }
}

what am i doing wrong? it puts the value of e in inputString correctly but then it doesn't change position so it keeps overwriting the letter

  • Please do not post an (two) actual sentence in the title, but a solid summarization. – hellow Sep 10 '18 at 08:38
  • [Don't cast the result of `malloc` in C](https://stackoverflow.com/q/605845/995714), please also read [ask] and make your post clearer as well as write a proper title – phuclv Sep 10 '18 at 09:17

1 Answers1

1

Mostly the main thing you're doing wrong is with this line:

string->inputString = &e;

That's replacing the memory you've allocated with a pointer to e, which is why it'll only ever be the last character. To add e to the current position, you need to index into the memory you've allocated like this:

string->inputString[currentStringLenght] = e;

although I imagine that currentStringLenght should probably be string->stringLength so you don't lose the value when this part of the code is done.

And you also need to add a NUL character when you've finished to complete your string as otherwise bad stuff will happen.

string->inputString[currentStringLenght] = '\0';
Chris Turner
  • 8,082
  • 1
  • 14
  • 18