在c中交换两个结构
Swapping two structures in 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]);
表达式 *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]);
你确实在尝试交换指针。
首先,您的片段中没有结构,只有指向结构的指针。因此,您所做的一切都是在尝试交换指针,而不是结构值。
Struct 通常在内存中的某处占用多个字节。指针是包含此内存地址的变量。它还占用一些内存,即 64 位地址占用 8 个字节。
以下是指向结构对象的指针数组。
struct StudentRecord *pSRecord[numrecords];
您使用结构对象数组中的地址对其进行了初始化。
这个调用看起来像是在尝试交换指向数组中结构的指针。你做对了。
swap(&pSRecord[0], &pSRecord[1]);
然而,由于 pSRecord[i] 已经是指向结构的指针,并且您获取指针的地址 &
,因此生成的对象将是指向结构指针的指针。因此,您的交换函数需要 **
,如下所示。你的其余代码是正确的:
void swap(struct StudentRecord **A, struct StudentRecord **B) {
struct StudentRecord *temp = *A;
*A = *B;
*B = *temp;
}
您好,我正在尝试创建一个交换函数来交换结构的前两个元素。有人可以告诉我如何进行这项工作吗?
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]);
表达式 *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]);
你确实在尝试交换指针。
首先,您的片段中没有结构,只有指向结构的指针。因此,您所做的一切都是在尝试交换指针,而不是结构值。
Struct 通常在内存中的某处占用多个字节。指针是包含此内存地址的变量。它还占用一些内存,即 64 位地址占用 8 个字节。
以下是指向结构对象的指针数组。
struct StudentRecord *pSRecord[numrecords];
您使用结构对象数组中的地址对其进行了初始化。
这个调用看起来像是在尝试交换指向数组中结构的指针。你做对了。
swap(&pSRecord[0], &pSRecord[1]);
然而,由于 pSRecord[i] 已经是指向结构的指针,并且您获取指针的地址 &
,因此生成的对象将是指向结构指针的指针。因此,您的交换函数需要 **
,如下所示。你的其余代码是正确的:
void swap(struct StudentRecord **A, struct StudentRecord **B) {
struct StudentRecord *temp = *A;
*A = *B;
*B = *temp;
}