Sahand K.

asked • 06/04/19

my code crashes in the second loop operation(C Programming)

its aim is to get a number from the user and create that number of kind of television programs and save their information based on structures.it gets the program name ,hour,etc

unfortunately it crashes after getting the name in the second loop


#include <stdio.h>

#include <stdlib.h>


struct time {

int hour;

int minute;

};

struct program {

char name[30];

struct time mytime;

int viewer[3];// baby woman man

int type;

} ;

void func (struct program *, int, int);

struct program * func2 (struct program *);

main()

{


int k, i;

printf("k=");

scanf("%d", &k);

struct program *p , *p1 , *p2;

int size = sizeof(struct program);

p = (struct program *) malloc (k * sizeof (struct program));


p1= p;

if (p != NULL)

{

for (i=0; i<k; i++)

{

printf("Name =");

scanf("%s", p->name);

//it crashes here !

printf("Hour=");

scanf("%d",&p->mytime.hour);

printf("Minute=");

scanf("%d",&p->mytime.minute);

printf("Type=");

scanf("%d",&p->type);

printf("Baby=");

scanf("%d",&p->viewer[0]);

printf("Woman=");

scanf("%d",&p->viewer[1]);

printf("Man=");

scanf("%d",&p->viewer[2]);

printf("-----------------------------------------------\n");

p += size;

}

}

p=p1;

func (p, size, k);


printf("Name =");

scanf("%s", p1->name);

printf("Hour=");

scanf("%d",&p1->mytime.hour);

printf("Minute=");

scanf("%d",&p1->mytime.minute);

printf("Type=");

scanf("%d",&p1->type);

printf("Baby=");

scanf("%d",&p1->viewer[0]);

printf("Woman=");

scanf("%d",&p1->viewer[1]);

printf("Man=");

scanf("%d",&p1->viewer[2]);

printf("-----------------------------------------------\n");

func2(p1);

printf("%s %d %d %d %d %d %d",p1->name ,p1->mytime.hour,p1->mytime.minute , p1->type ,

p1->viewer[0], p1->viewer[1],p1->viewer[2]);

return 0;

}


void func (struct program *p, int size, int k)

{

int i, s;

for (i=0; i<k; i++)

{

s = 0.2*(p->viewer[0] + p->viewer[1] + p->viewer[2]);

if ( p->viewer[0] > s )

p->type= 1;

if (p->mytime.hour > 14 )

{

printf("Name=%s Hour=%d Minute=%d\n",p->name ,p->mytime.hour,p->mytime.minute);

}

p += size;

}

}

struct program * func2 (struct program *p)

{

if (p->viewer[1] > p->viewer[2])

{

p->type = 3;

return p;

}

}


ps : my code is in c programming language

ps 2 : sorry for my grammar mistakes!!!

1 Expert Answer

By:

Still looking for help? Get the right answer, fast.

Ask a question for free

Get a free answer to a quick problem.
Most questions answered within 4 hours.

OR

Find an Online Tutor Now

Choose an expert and meet online. No packages or subscriptions, pay only for the time you need.