I have this code for now:
pacient sortClients(int n, pacient *lista, int print)
{
pacient aux[50];
for(i=0;i<n;i++)
*(aux+i)=*(lista+i);
//some modifications performed on aux
return *aux;
}
void sortAndShowByAge(int n, pacient *lista)
{
pacient aux[50];
*aux=sortClients(n,lista,0);
}
The last function is where I get in trouble. If aux has only one record then it works ok, if there are more than two, it shows some weird characters. In the first function I iterated over lista and saved every record to aux. Is there a way to assign the aux from sortClients to aux in shortAndShowByAge directly and not iterate? I can’t iterate over sortClients.
Your code simply returns a single element, rather than the entire array. It can’t legally return the array as written, since it’s a local variable.
You need to either allocate new memory dynamically, or sort in-place.
The former, which is most like what you have already, would go like this:
This returns a pointer to the sorted/processed array, which you must call
free()on when you’re done with, in order not to leak memory.I alao corrected the return type, and use
memcpy()instead of a manual loop to copy the input values. The input array is marked asconsttoo, since it’s read-only for the function.