#Seg Fault when asking user for input

14 messages · Page 1 of 1 (latest)

frail kindle
#

The code is asking the user for input. The input will then be converted to a int however I am getting a seg fault pointing to Line:12 fgets(userInput, 2, stdin). Why is it so?

#include <stdio.h>
#include <stdlib.h>

int main() {
    // Write C code here
    char *userInput;
    int userChoice;
    
    printf("No: ");

    int c;
    fgets(userInput, 2, stdin);
    while ((c = fgetc(stdin)) != '\n' && c != EOF);

    userChoice = atoi(userInput);

    return 0;
}
bright daggerBOT
#

When your question is answered use !solved to mark the question as resolved.

Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question run !howto ask.

lyric knot
#

char * is a pointer to char, and you need a buffer, e.g. array

#

use compiler warnings and even error on them

frail kindle
lyric knot
#

pointer just keeps address to something, fgets requires pointer to array of char

frail kindle
#

here is the code snip of the other project which worked

hangman player1() {
    char *word = malloc(50);
    char *guess = calloc(100, 1);
    char *strLives;
    int lives;

    system("cls");
    printf("----------------- HANGMAN -----------------\n\nPlayer 1 - Enter a word to be guessed: ");
    fgets(word, 50, stdin);

    word[strcspn(word, "\n")] = '\0';  // remove (possibly) trailing newline
    
    for (int i = 0; word[i]; i++) {
        guess[i * 2] = '_';
        guess[i * 2 + 1] = ' ';
    }

    printf("How many lives should the player have: ");
    fgets(strLives, 10, stdin);
    lives = atoi(strLives);
    
    return (hangman) { word, guess, lives };
}
lyric knot
#

but a pointer declared like that, uninitialized, doesn't point to anywhere particular

#

well, that fragment uses malloc and calloc, which reserve a buffer in memory, although this is not the solution you're looking for

#

you are looking for answer what array is and how to declare one

frail kindle
#

ok i got it, thx

#

!closed

#

!solved