I am trying to create a struct using dynamic memory allocation,get input at run time and finally trying to print out the contents.
This is the code:
#include<stdio.h>
#include<stdlib.h>
typedef struct island{//struct template
char* name;
char* opens;
char* closes;
struct island *next;
}island;
void display(island *start)//start display
{
island *i;
i=start;
while(i!=NULL)
{
printf("Name:%sOpen:%s-%s\n",i->name,i->opens,i->closes);
i=i->next;
}
}//end display
island *create(char *name)//start create
{
island *i=malloc(sizeof(island));
i->name=strdup(name);
i->name=name;
i->opens="9:00AM";
i->closes="5:00PM";
i->next=NULL;
return i;
}//end create
int main()//start main
{
char name[80];
fgets(name,80,stdin);
island *i=create(name);
display(i);
return 0;
}//end-main
What we have here is an island struct,a display method to display the struct contents and then a create function which creates the space for the struct using dynamic memory allocation.I pass the name for the island at runtime and create the struct.
This is the output which I get and it works when I run the program:
C:\Users\Gova\Desktop\ctest>testing
Ami
Name:Ami
Open:9:00AM-5:00PM
Note:testing is the name of the program.
The problem is I am trying to print the output in this manner,and its not getting printed,why is that?
C:\Users\Gova\Desktop\ctest>testing
Ami
Name:Ami Open:9:00AM-5:00PM
printf() statement used is:
printf("Name:%sOpen:%s-%s\n",i->name,i->opens,i->closes);
Why does the program add a line break when I have not specified anything in the printf() statement?