Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Unexpected Output plus segmentation error with my C program

I am trying to learn programming and was trying the following code in C. However, As you can see below I am not getting the expected output and I am getting a segmentation error while trying out solutions :

I feel I am doing something wrong with the declaration of First name or something. But not able to figure it out.

My Code:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

#include <stdio.h>

int main(void){
    char first_name;
    printf("Enter your name: \n");
    scanf("%c", &first_name);
    printf("Hello, %c", first_name);
}

Actual Output

This is the output I am currently getting:

Enter your name: 
asdasfasf
Hello, a

Expected Output

Enter your name: 
asdasfasf
Hello, asdasfasf

>Solution :

Here is my answer

#include <stdio.h>

int main(void){    
        char first_name[100] = {0}; 
        printf("Enter your name:(Max length is 99)\n"); 
        scanf("%99s", first_name); 
        printf("Hello, %s\n", first_name); 
}

Run it will output

Enter your name:(Max length is 99)
asdasfasf
Hello, asdasfasf
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading