【发布时间】:2017-10-05 18:55:00
【问题描述】:
您好,我正在尝试创建一个交换函数来交换结构的前两个元素。有人可以告诉我如何使这项工作。
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]);
【问题讨论】:
-
最好将
temp设为值,而不是指针。 -
struct StudentRecord *temp = *A;-->struct StudentRecord temp = *A;..*B = *temp;-->*B = temp;.....swap(&pSRecord[0], &pSRecord[1]);-->swap(pSRecord[0], pSRecord[1]);或swap(&SRecords[0], &SRecords[1]); -
除此之外:不是每个人都厌倦了包含“学生”的 C 代码。所以世界各地的所有老师都布置相同的作业?
-
@FredLarson:指针是值。
-
@Olaf:当然,我指的是结构的值。