Scanf parsing string input into array of chars

前端 未结 3 1560
失恋的感觉
失恋的感觉 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]);
    }
    

提交回复
热议问题