简体   繁体   中英

Using struct and strcpy, program crashes

Hello this is my first time posting on this site and also I am not very familiar with structures or with strcpy() I was wondering why my program below is crashing.

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>

struct Employee{
    char name[30];
    char email[30];
};

void main(){
    struct Employee x;
    char employee_name[30];
    char employee_email[30];

    printf("enter the employees's name\n");
    fgets(employee_name,30,stdin);
    strcpy(x.name, employee_name);

    printf("enter the employee's email\n");
    fgets(employee_email,30,stdin);
    strcpy(x.email,employee_email);

    printf('%s',x.name);
    printf('%s',x.email);
}

The purpose of the program is basically to accept a name and email as input and put it in the name and email of the structure and than print them using the structure. Now the program compiles and allows me to take the input but after that it crashes and I do not know why. Does anyone know why the crash is occurring?

The issue is with

printf('%s',x.name);
printf('%s',x.email);

as per the printf() format,

int printf(const char *format, ...);

the fisrt argument is a const char * . So, you need to write

printf("%s",x.name);
printf("%s",x.email);

That said,

  • void main() should be int main(void) , at least to conform to the standards.
  • fgets() scans and stores the trailing newline (if any) to the input buffer as a part of the input. You may want to strip it off before copying the buffer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM