segmentation fault in C

I am trying to write this code, but it gives me segmentation fault after running the program, could you please help to sort it out?

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

typedef struct{
    int salary;
    char* name;
} employee ;

int main(){
    employee p[2];
        int i;
        for(i=0;i<2; i++){
            printf("enter sal ");
            scanf("%d", &p[i].salary);

           printf("enter name ");
           scanf("%s", &p[i].name);
        for(i=0;i<2; i++){
           printf("p %d",p[i].salary);
           printf("p %s",p[i].name);
    return 0;


The structure field name is just a wild character pointer.

char* name;

you are reading the user input as:

scanf("%s", &p[i].name);

into the memory pointed by name which could be anywhere.

To fix this you need to dynamically allocate memory pointed to by name or you can change name to a char array of size one greater than the max length of the name possible.

char name[MAX];

  • You need to allocate memory for the name field: p[i].name = (char*)malloc(MAX_NAME_LEN)
  • Also, the scanf("%s", &p[i].name) should read scanf("%s", p[i].name).

You don't need the & operator when scanf'ing to pointer. And you need to malloc p[i].name

       scanf("%s", p[i].name);

You are not allocating memory for char* name. change your data structure to

typedef struct
    int salary; 
     char name[50]; 

or allocate memory using malloc

Need Your Help

.htaccess point file on one subdomain to another

.htaccess mod-rewrite

What's the best way to re-point files from one sub-domain to another with use of htaccess as illustrated in below example.

Replicating request to Chef with Python RSA

python openssl rsa chef

Goal: I need a Python 3 wrapper for Chef's REST API. Because its Python-3, PyChef is out of the question.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.