r/C_Homework • • Nov 17 '17

Array issues

Hello I'm new to C program trying get a school project done. Sample of the code that isn't working as intended:

printf("Please enter the number of Consultation session:\n");
scanf("%d", &consultation);

hour =(int *) malloc((consultation+1) * sizeof(int));
if (hour == NULL)
    {
        printf("Insufficient memory.\n");
            return;
    }

//counting frequency size of sessions
for (count = 0; count < attendance; ++count)
    {
    	++hour[num[count].sessions];//not working
    }

My num[count].sessions is calling values from 'sessions' which is inside a struct defined by num. Why does my array 'hour' not tracking the frequency of the value from 'sessions' being called up?

edit:formatting

1 Upvotes

5 comments sorted by

View all comments

Show parent comment

3

u/jedwardsol Nov 17 '17

After calling malloc you need to initialise the contents

int *hour= (int *) malloc((consultation+1) * sizeof(int));

for(count = 0; count < (consulation + 1); count++)
{
    hour[count]=0;
}

Why? Because.

The specification for malloc doesn't say that it must guarantee the memory contains anything specific, so it doesn't.

2

u/mh3f Nov 17 '17

Or use calloc

1

u/Tinymaple Nov 18 '17

Hey thank you for the explanation! I'll keep this in mind next time when i'm writing the code!