I have this code were i need to sort an array of struct without modifying it. I passed the array of struct by value and i used an int array with indexes to sort the struct. To sort the array i also need to sort the struct, which is passed by value in the function, if i am not wrong, if you modify a value passed by value in a funtion it still is the same in the main, but in the main it changes, and when i try to print the struct array using the sorted array of indexes it doesn't print it sorted becouse the array of struct is sorted(as i said before, to sort the indexes i need to modify the array of struct).
I expected that the struct array doesn't get modified if i pass it as value.
this is the function, after this will be the chunk of code where i use the function.
void Opartenza(struct Corse c[], int d, int **O)
{
int temp = 0;
O[0] = (int *)malloc(d * sizeof(int));
for(int i = 0; i < d; i++)
O[0][i] = i;
for(int i = 0; i < d; i++)
{
for(int j = 0; j < d - 1; j++)
{
if(strcmp(c[j].partenza, c[j + 1].partenza) > 0)
{
temp = O[0][j];
O[0][j] = O[0][j + 1];
O[0][j + 1] = temp;
c[d] = c[j];
c[j] = c[j + 1];
c[j + 1] = c[d];
}
}
}
}
case r_o_partenza:
Opartenza(corse, dim, &Ordinamento);
for(int i = 0; i < dim; i++)
printf("%s\n", corse[i].partenza);
break;
As you see i tried to print the array of struct, and it is sorted as the array of indexes.
In C arrays are always passed by reference, no matter what, as internally indexing an array compiles down to pointer arithmetics. That means, that passing an array with array notation or a pointer to an array, really boils down to the same thing. If you really want your array to not be modified copy it first.