Scanf parsing string input into array of chars

前端 未结 3 1524
失恋的感觉
失恋的感觉 2021-01-24 09:14

I want to parse a user-input (using scanf) in 2 separate arrays. g++ compiles without error, but I get a memory-access-error (core dumped). (in german: \"Speicherzugriffsfehler

3条回答
  •  清酒与你
    2021-01-24 10:16

    You haven't allocated memory for your strings. The arguments you give to scanf are uninitialized pointers.

    top[i] = "test" assigns a pointer to your variable and initializes it with a valid value.

    In contrast, scanf(..., top[i]) tries to write to where top[i] points. But top[i] isn't initialized and points to some random location, which results in your memory access error.

    When you look at man scanf, you can read under

    Conversions
    ...
    s
    Matches a sequence of non-white-space characters;

    and now the important part

    the next pointer must be a pointer to character array that is long enough to hold the input sequence and the terminating null byte ('\0'), which is added automatically.

    So you must allocate an array via malloc() or declare the character array large enough.

    char top[10][21];
    char bottom[10][21];
    int i;
    for(i = 0; i < 5; i++){
        printf("Karte %d: Obere Werte? ", i);
        scanf("%20s",top[i]);
        printf("Karte %d: Untere Werte? ", i);
        scanf("%20s",bottom[i]);
    }
    

    With

    scanf("%20s",top[i]);
    

    you limit the number of characters read, to prevent a buffer overrun

提交回复
热议问题