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(struct StudentRecord *A, struct StudentRecord *B){
struct StudentRecord *temp = *A;
*A = *B;
*B = *temp;
}
struct StudentRecord *pSRecord[numrecords];
for(int i = 0; i < numrecords; i++) {
pSRecord[i] = &SRecords[i];
}
printf("%p \n", pSRecord[0]);
printf("%p \n", pSRecord[1]);
swap(&pSRecord[0], &pSRecord[1]);
printf("%p \n", pSRecord[0]);
printf("%p \n", pSRecord[1]);
First of all you do not have structs in your fragment, just the pointers to the structs. Therefore everything you do there is an attempt to swap pointers, not the struct values.
Struct usually occupies multiple bytes somewhere in memory. A pointer is a variable which contains an address of this memory. It also occupies some memory, i.e. 8 bytes for a 64-bit address.
The following is an array of pointers to the struct objects.
which you initialized with addresses from the array of struct objects.
This call looks like an attempt to swap pointers to the structs in your array. You did it correctly.
however since pSRecord[i] is already a pointer to the struct and you take an address of the pointer
&
, the resulting object will be pointer to a pointer to a struct. Therefore your swap function needs**
, like the following. And the rest of your code is correct:The expression
*A
has typestruct StudentRecord
while the nametemp
is declared as having typestruct StudentRecord *
. That istemp
is a pointer.Thus the initialization in this declaration
does not make sense.
Instead you should write
As result the function will look like
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
If you want to swap the pointers themselves then the function will look like
And in this statement
you are indeed trying to swap pointers.