openlang

Inputting character arrays through pointers

Whenever I attempt keyboard input into some char arrays, my program ends up crashing.

What's a straightforward way of reading char arrays from the keyboard and saving them?

int main() {
    int pos;
    char *labels[8];
    for (pos=0; pos<8; ++pos) {
        scanf("%s",labels[pos]);
    }
    for (pos=0; pos<8; ++pos) {
        printf("%s\n",labels[pos]);
    }
    return 0;
}

The conversation continues 2

Follow the reasoning
  1. Permalink

    The declaration char *labels[8] creates a pointer array. Without initialization to a valid address, those pointers designate invalid locations in memory. Consequently, attempting writes through them results in undefined behaviour.

    Before using those pointers, make certain that they reference valid allocated memory locations.

  2. Permalink

    Those pointers form an array pointing to char, but they aren't referncing any valid memmory.

    First allocate storage for those pointers:

    int main(void)
        int pos;
        char *labels[8];
        for (pos=0; pos<8; ++pos) {
            labels[pos]=malloc(LABELCAP);
            scanf("%17s",labels[pos]);
        }
        for (pos=0; pos<8; ++pos) {
            printf("%s\n",labels[pos]);
            free(labels[pos]);
        }
        return 0;
    }

    another option is

    int main(void) {
        int pos;
        char labels[8][LABELCAP];
        for (pos=0; pos<8; ++pos) {
            scanf("%17s",labels[pos]);
        }
        for (pos=0; pos<8; ++pos) {
            printf("%s\n",labels[pos]);
        }
        return 0;
    }

Other sides of the same question

  1. Same sink call, a copy on one line and a move on the next

    Nim 2 decides copy or move per call site. Not per proc. Same argument, same proc. The first call copies, because a is still n…

    Replies 2Latest activity nim
  2. Delaying a cleanup block's mutable borrow until it actually runs

    What would be a way for me to write a panic-safe mecanism in Rust that behaves similarly to Java's try { ... } finally { ...…

    Replies 2Latest activity rust
  3. Can an input function avoid relying on global variables?

    I'd like a function to process what a user enters, filter it, and return the resulting string to whichever function called it…

    Replies 2Latest activity c