How to Initialize structure member variables in C C++

Ways of initializing a structure in C and C++. How not to do mistake in initializing structures.
#include<stdio.h>
#include<memory.h>
struct employee
{
int id;
char name[20];
//Note that below ways of initializing structure is error.
//int id=10;//erro:because memory is not allocated for structure here.
//strcpy(name,"Ram");//error for same reason.
};

int main()
{
//one way of initializing structure.
struct employee e1={1000,"Leal"};//one way of initializing structure.
printf("Employee details:\n");
printf("id=%d, name=%s\n",e1.id,e1.name);


//Another way of initializing structure.
struct employee e2;
e2.id=1001;
strcpy(e2.name,"Mitra");
printf("\nEmployee details:\n");
printf("id=%d, name=%s\n",e2.id,e2.name);

//Yet another way of initializing  structure.
struct employee e3;
printf("Enter id :\n");
scanf("%d",&e3.id);
printf("Enter name :\n");
scanf("%s",&e3.name);
printf("\nEmployee details:\n");
printf("id=%d, name=%s\n",e3.id,e3.name);
return 0;
}
/******* OUTPUT
@ubuntu:~/headHunt$ gcc structureInitialization.c 
structureInitialization.c: In function ‘main’:
structureInitialization.c:30:1: warning: format ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘char (*)[20]’ [-Wformat]
@ubuntu:~/headHunt$ gcc structureInitialization.c 
structureInitialization.c: In function ‘main’:
structureInitialization.c:30:1: warning: format ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘char (*)[20]’ [-Wformat]
@ubuntu:~/headHunt$ ./a.out 
Employee details:
id=1000, name=Leal

Employee details:
id=1001, name=Mitra
Enter id :
200
Enter name :
blog

Employee details:
id=200, name=blog
@ubuntu:~/headHunt$ 
*****************/

1 comment:

  1. Structure data member variable within structure, yes we can initialize member of structure inside structure itself. And constructor in c++ makes it possible.
    struct lealmitra
    {
    //int empid=0;//error cant initialized like this inside structure.
    public:
    lealmitra()
    {
    int empid=0;//correct.
    }
    };

    ReplyDelete