使用指针交换两个数组

时间:2017-11-21 01:53:18

标签: c arrays pointers

我想知道为什么下面的代码不起作用。我已经使用指针将数组从一个复制到另一个,但它根本不复制。我错过了什么吗?

#include <stdio.h> 
typedef struct student {
    int id;
    char *pname;
    double points;
} STUD;

void stud_printx(STUD s) {
    printf("[%d:%s] = %lf\n", s.id, s.pname, s.points);
}

void stud_swap(STUD *s1, STUD *s2) { // space to be filled - my code written
STUD tmp;
     tmp = *s1;
     *s1 = *s2; 
     *s1 = tmp;    


}

int main(void) {
    STUD s1 = {1, "Choi", 9.9};
    STUD s2 = {2, "Park", 0.1};

    stud_printx(s1);
    stud_printx(s2);

    stud_swap(&s1, &s2 ); // space to be filled  - my code written 

    stud_printx(s1);
    stud_printx(s2);

    return 0;
}

1 个答案:

答案 0 :(得分:2)

*s1 = *s2;  // Copy original *s2 into *s1
*s1 = tmp;  // Copy original *s1 into *s1

应该是

*s1 = *s2;  // Copy original *s2 into *s1
*s2 = tmp;  // Copy original *s1 into *s2