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?
1 Answer 1
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]);
}
s.num_grades- this is definitely not initialized. And you need to includestdlib.hs.num_gradesin the argument tomalloc, but you never gave it a value. It is undefined. Either don't use it, or else assign something to it first. (2) You're assigning top->grades[0]without settingpfirst. So setpto some valid pointer value first. If you don't understand what pointers are, then take a step back and find a C tutorial to learn about them.arr->grades = 90;is wrong.gradesis a pointer to an array of grades, not a single grade.p = &s?