I am supposed to follow the following criteria:
Implement function answer4 (pointer parameter and n):
-
Prepare an array of student_record using
malloc()of n items. -
Duplicate the student record from the parameter to the array n
times. -
Return the array.
And I came with the code below, but it’s obviously not correct. What’s the correct way to implement this?
student_record *answer4(student_record* p, unsigned int n)
{
int i;
student_record* q = malloc(sizeof(student_record)*n);
for(i = 0; i < n ; i++){
q[i] = p[i];
}
free(q);
return q;
};
This is problematic: you’re overwriting the
pinput argument, so you can’t reference the data you were handed after that line.Which means that your inner loop reads initialized data.
This:
is problematic too – it would return a pointer to a local variable, and that’s not good – that pointer becomes invalid as soon as the function returns.
What you need is something like: