Scanf parsing string input into array of chars

前端 未结 3 1525
失恋的感觉
失恋的感觉 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:12

    As another answer says, you have to allocate place for your strings. You want an array of top and bottom strings, but with char * top[10] you are only allocating room for 10 pointers, not for the characters in the strings. The reason why top[10] = "Hello" works is that string literals are implicitly allocated by the compiler, which returns a pointer to those characters.

    char *top[10], *bottom[10];
    for(i = 0; i < 5; i++)
    {
        top[i] = malloc(100); // reserve room for string up to 100 chars
        printf("Karte %d: Obere Werte? ", i);
        scanf("%s",top[i]);
        bottom[i] = malloc(100);
        printf("Karte %d: Untere Werte? ", i);
        scanf("%s",bottom[i]);
    }
    
    0 讨论(0)
  • 2021-01-24 10:14

    What you have is an array of pointers. You need to allocate memory for each pointer in array.

    You can do the following before scanf.

    top[i] = malloc(sizeof(char)*255);
    bottom[i] = malloc(sizeof(char)*255);
    

    After use don't forget to free.

    free(top[i]);
    free(bottom([i]);
    
    0 讨论(0)
  • 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

    0 讨论(0)
提交回复
热议问题