Reputation: 27
I have the following code:
#include<stdio.h>
struct student {
int* grades;
int num_grades;
};
double* get_means(struct student* arr, int n); // Function Signature
// grade range is: 0 - 100
// assume max number of grades to one student is up to 100
double* get_means(struct student* arr, int n)
{
arr->grades = 90;
printf("%d", arr->grades);
}
int main()
{
struct student s, *p;
s.grades = malloc(s.num_grades * (sizeof(int)));
p->grades[0] = 1;
printf("%d", p->grades[0]);
}
and I'm having an issue assigning a value (it doesn't matter what the value is, it can be: 0, 7, 50).
The compiler gives me the error:
Error C4700 uninitialized local variable 's' used
Error C4700 uninitialized local variable 'p' used
What can I do to fix this?
In other words: how do I assign a value to an array in a struct?
Upvotes: 1
Views: 100
Reputation: 474
When you try to do that p->grades[0] = 1 first you need to assign the address for s to p and only than trying to access s from the pointer p. Second issue here is you trying to access array only through is name (in the function get means), As you know array name its only the base address of the array its not the value in it. Third issue its the function does not return nothing but in the prototype it returns pointer to double, I suggest you to change it to avoid any unnecessary warnings or errors. And another suggestion is including <stdlib.h> when using malloc and always check malloc does not returns you NULL.
The fixed code attached:
struct student {
int* grades;
int num_grades;
};
void get_means(struct student* arr, int n);
void get_means(struct student* arr, int n)
{
arr->grades[0] = 90;
printf("%d", arr->grades[0]);
}
int main()
{
struct student s, *p;
s.grades = malloc(s.num_grades * (sizeof(int)));
/* Option 1
s.grades[0] = 1;
printf("%d", s.grades[0]);
*/
/* Option 2 */
p = &s;
p->grades[0] = 1;
printf("%d", p->grades[0]);
}
Upvotes: 1