//struct and typedef
#include <stdio.h>
#include <string.h>
/*
There’s two different situations here depending on
whether we dynamically feed the struct or not.In this
piece of code lets check out how we can use struck in manual memory management
*/
typedef char abc;
//What i did here with typedef is that i took data type char and defined it with another name in this case “abc”
typedef struct entry
{
abc name[15];
abc surname[15];
unsigned short int age;
}ENTRY;
ENTRY a,b;
/*
struct entry
{
abc name[15];
abc surname[15];
abc adress[50];
unsigned short int age;
}abraham,bob;
abraham and bob are variables here in type of entry(that’s what we chose to call our struct,if you
pull your mouse onto abraham(in Visual Studio) you’ll see “entry abraham” but
if i write my struct column like this:
typedef struct entry
{
abc name[15];
abc surname[15];
abc adress[50];
unsigned short int age;
}ENTRY;
Then “ENTRY” here would be the name of struct we just create(if you ask why do this instead of the other version,
once we do this we don’t have to write:
struct entry new_entry; to create variable “new_entry”.
All we have to is this:
ENTRY new_entry; )
and if you
pull your mouse onto ENTRY (in Visual Studio) you’ll see “typedef entry ENTRY”.
*/
int main(){
strcpy_s(a.name,”Andrew”);
strcpy_s(a.surname,”Lincoln”);
a.age=35;
strcpy_s(b.name,”Bob”);
strcpy_s(b.surname,”Birch”);
b.age=60;
//check
printf(“***Entry A***\nName:%s\nSurname:%s\nAge:%d\n”,a.name,a.surname,a.age);
printf(“***Entry B***\nName:%s\nSurname:%s\nAge:%d”,b.name,b.surname,b.age);
getchar();
return 0;
}
Here’s the output:
//And this is the one with dynamic mem.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct record
{
char name[15];
char surname[15];
unsigned short int age;
}RECORD;
RECORD * p=(RECORD*)malloc(sizeof(RECORD));
int main(){
strcpy_s(p->name,”Francis”);
strcpy_s(p->surname,”Underwood”);
p->age=60;
//check
printf(“***Record***\nName:%s\nSurname:%s\nAge:%d”,p->name,p->surname,p->age);
getchar();
free(p);
return 0;
}
Here’s the output: