0

I've a big problem. I created a variable array with struct. For that I've used malloc and realloc.

But if I'm using scanf ,the console isn't waiting for a second input and is moving forward. How can I solve this problem.

#include <string.h>
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>

typedef struct {
    float feuchtewert;
    float temperaturwert;
    char zeitstempel[8];
} T_DHT22;



int main()
{
    int length = 1;
    T_DHT22 *messreihe = malloc(length * sizeof(*messreihe));

    bool weiterErstellen = true;

    while(weiterErstellen) {

        char c = 'n';
        printf("Weiteren Messwert erstellen? <y|n>");
        scanf("%c", &c);

        if(c == 'y') {
            length++;
            messreihe = realloc(messreihe, length * sizeof(*messreihe));

            printf("\nFeuchtewert: ");
            scanf("%.2f", messreihe[length].feuchtewert);
            printf("\nTemperaturwert: ");
            scanf("%.2f", messreihe[length].temperaturwert);
            //gets(messreihe[length].zeitstempel);

        }else {
            weiterErstellen = false;
        }


    }

    free(messreihe);
    //sort_and_calcAvg(messreihe, length);

}
Jabberwocky
  • 48,281
  • 17
  • 65
  • 115
Bowixel
  • 3
  • 1
  • 3
  • `"%.2f"` -> `"%f"`. – Jabberwocky Feb 18 '21 at 13:28
  • @Jabberwocky Now I'm getting this error: Process returned -1073741819 (0xC0000005) execution time : 4.730 s – Bowixel Feb 18 '21 at 13:30
  • Also in your scanfs you forgot the `&`: `&messreihe[length].feuchtewert`. And there is an off by one error when you access `messreihe[length]`, it should be `messreihe[length - 1]`. Array indexes start with 0. – Jabberwocky Feb 18 '21 at 13:33
  • @Jabberwocky Thank you. Now he is accepting "Feuchtewert", "Temperaturwert" and "Zeiitstempel" BUT on the loop pass he is not waiting for the "char c" input. What can i do? – Bowixel Feb 18 '21 at 13:48
  • 1
    Please change `scanf("%c", &c);` with an added space to `scanf(" %c", &c);` See [scanf() leaves the newline char in the buffer](https://stackoverflow.com/questions/5240789/scanf-leaves-the-new-line-char-in-the-buffer). – Weather Vane Feb 18 '21 at 13:48
  • Oh boy xD. Thank you. That was really dumb. – Bowixel Feb 18 '21 at 13:51
  • 1
    No, it's just that `scanf` is complicated. Some explanation: most of the format specifiers for `scanf` automatically filter leading whitespace, but `%c` and `%[]` and `%n` do not. Adding a space in front of the `%` instructs `scanf` to filter leading whitespace here too. – Weather Vane Feb 18 '21 at 13:51
  • Either way, You've secured my day. – Bowixel Feb 18 '21 at 13:57

0 Answers0