passing an array of strings to a function where the strings are taken from the user

You must allocate some buffer for strings before using pointers.

int main(){

    char *stringArray[3];

    for(int i=0; i<3; i++){
        stringArray[i] = malloc(1024 * 1024); /* allocate buffer, hoping user input won't be so long */
        if (stringArray[i] == NULL) { /* check if allocation is successful */
            perror("malloc");
            return 1;
        }
        scanf("%s", stringArray[i]);
    }

    print(stringArray, 3);

    for(int i=0; i<3; i++){
        free(stringArray[i]); /* free allocated things */
    }

    return 0;
}

For more information, see c – Crash or “segmentation fault” when data is copied/scanned/read to an uninitialized pointer – Stack Overflow

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top