0

i I was wondering why code below doesn't work. I have used pointer to copy array from one to another but it doesn't copy at all. Am I missing something?

#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;
}
3
  • Not every student is a stud :) Commented Nov 21, 2017 at 1:55
  • 1
    Re "I have used pointer to copy array", huh, there's no array in that program. Commented Nov 21, 2017 at 1:57
  • Voting to close as typo - it seems clear that you had *s2 = tmp; in mind but just didn't type it out right Commented Nov 21, 2017 at 3:53

1 Answer 1

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

should be

*s1 = *s2;  // Copy original *s2 into *s1
*s2 = tmp;  // Copy original *s1 into *s2
Sign up to request clarification or add additional context in comments.

1 Comment

I've looked over the code again and just noticed the mistake. Thank you!!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.