Hi i\'m trying to create a swap function that swaps the first two elements of the structure. Can someone please show me how to make this work.
void swap(struc
The expression *A
has type struct StudentRecord
while the name temp
is declared as having type struct StudentRecord *
. That is temp
is a pointer.
Thus the initialization in this declaration
struct StudentRecord *temp = *A;
does not make sense.
Instead you should write
struct StudentRecord temp = *A;
As result the function will look like
void swap(struct StudentRecord *A, struct StudentRecord *B){
struct StudentRecord temp = *A;
*A = *B;
*B = temp;
}
Take into account that the original pointers themselves were not changed. It is the objects pointed to by the pointers that will be changed.
Thus the function should be called like
swap(pSRecord[0], pSRecord[1]);
If you want to swap the pointers themselves then the function will look like
void swap(struct StudentRecord **A, struct StudentRecord **B){
struct StudentRecord *temp = *A;
*A = *B;
*B = temp;
}
And in this statement
swap(&pSRecord[0], &pSRecord[1]);
you are indeed trying to swap pointers.