2017-10-05 69 views
0

嗨,我想创建一个交换函数,交换结构的前两个元素。有人可以告诉我如何使这项工作。交换c中的两个结构

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]); 
+2

最好让'temp'成为一个值,而不是指针。 –

+1

'struct StudentRecord * temp = * A;' - >'struct StudentRecord temp = * A;'''* B = * temp;' - >'* B = temp;'.....'swap (pSRecord [0],&pSRecord [1]);' - >'交换(pSRecord [0],pSRecord [1]);'或'交换(&SRecords [0],&SRecords [1]);' – BLUEPIXY

+0

一旁:并不是每个人都厌倦了包含“学生”的C代码。那么所有的老师都会在全世界做同样的任务吗? –

回答

4

表达*A具有类型struct StudentRecord而名称temp被声明为具有类型struct StudentRecord *。那是temp是一个指针。

因此,在此声明

struct StudentRecord *temp = *A; 

初始化没有意义。

相反,你应该写

struct StudentRecord temp = *A; 

由于产生的功能将类似于

void swap(struct StudentRecord *A, struct StudentRecord *B){ 
    struct StudentRecord temp = *A; 
    *A = *B; 
    *B = temp; 
} 

考虑到原来的指针本身并没有改变。指针所指向的对象将被改变。

这样的功能应该被称为像

swap(pSRecord[0], pSRecord[1]); 

如果你想交换指针本身则函数看起来像

void swap(struct StudentRecord **A, struct StudentRecord **B){ 
    struct StudentRecord *temp = *A; 
    *A = *B; 
    *B = temp; 
} 

而在此声明

swap(&pSRecord[0], &pSRecord[1]); 

你的确在尝试交换指针。

2

首先,你没有在你的片段中的结构,只是指向结构的指针。因此,你在那里做的每件事都是试图交换指针,而不是结构值。

结构通常占用内存中某处的多个字节。指针是一个包含该内存地址的变量。它也占用一些内存,即一个64位地址的8个字节。

以下是指向结构对象的指针数组。

struct StudentRecord *pSRecord[numrecords]; 

你用结构对象数组中的地址初始化它。

此调用看起来像是试图将指针交换到数组中的结构。你做得对。

swap(&pSRecord[0], &pSRecord[1]); 

然而由于pSRecord [i]是已的指针struct和你把指针&的地址,所得到的物体将是指针的指针到一个结构。因此,您的交换功能需要**,如下所示。而你的代码的其余部分是正确的:

void swap(struct StudentRecord **A, struct StudentRecord **B) { 
    struct StudentRecord *temp = *A; 
    *A = *B; 
    *B = *temp; 
} 
0

就像@Serge说,他的答案,它看起来像你正在尝试做的是交换指针。要做到这一点,如果你想能够交换指针,你需要传递指向指针的指针。从那里,还有一个巧妙的逻辑运算符小窍门,允许在不使用任何额外空间的情况下交换两部分数据。

void swap(struct StudentRecord **A, struct StudentRecord **B){ 
    *A ^= *B; 
    *B ^= *A; 
    *A ^= *B; 
} 

为什么它的工作原理:开始的初始值AB。我们将它们放在一起并将它们存储回A.我们将这个电话A'XORA'B并将其存储在B,我们应称之为B'。最后,XORA'B',并存储在A,我们应称之为A''

A'' = A' XOR B' 
B' = A' XOR B 
A' = A XOR B 

因此

A'' = A' XOR A' XOR B 
B' = A XOR B XOR B 

随着XOR化子性质,我们知道什么XOR倒是与本身是0,和任何XOR倒是有0本身,这给了我们:

A'' = B 
B' = A 
+1

既然何时对结构有意义? –

+0

@LeeDanielCrocker从那时起,我没有得到足够的睡眠。的Bleh。我将编辑它来处理指向结构的指针。 –

+0

无论如何XOR解决方案是可怕的。上个世纪的把戏。 –