Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 More on pointers. Example 1 – pass by value/reference int main(){ int p, q, r; p = 5; q = 6; r = Sum_1(p, q + 1); return 0; } void Sum_1(int a, int.

Similar presentations


Presentation on theme: "1 More on pointers. Example 1 – pass by value/reference int main(){ int p, q, r; p = 5; q = 6; r = Sum_1(p, q + 1); return 0; } void Sum_1(int a, int."— Presentation transcript:

1 1 More on pointers

2 Example 1 – pass by value/reference int main(){ int p, q, r; p = 5; q = 6; r = Sum_1(p, q + 1); return 0; } void Sum_1(int a, int b){ int c; c = a + b; return c; } pqr 56 200020042008 abc 400040044008 5 712

3 Example 2 – pass by value/reference int main(){ int *x,*y; int p = 5; int q = 6; x = &p; y = &q; Sum_1(p, y); return 0; } void Sum_1(int a, int *b){ int input; printf(“Enter an integer:”); scanf("%d", &input); *b = a + input; } xypq 5 2000200420082012 6 abinput 400040044008 15 2008 2012 5 2012 20

4 Example: Array and pointer int a[5]; int *p; int i = 0; for(i=0; i < 5; i++) a[i] = 3 + i; p= a; p = (int *)malloc(3 * sizeof(int)); a[0]a[1]a[2]a[3]a[4]p 200020042008201220162020 3 4 5 6 7 2000 p[0]p[1]p[2] 800080048008 8000 Heap (space for dynamically allocated data) Statically allocated data

5 Example 3: pointer to a struct int main(){ Student john; Student * john_ptr = &john; john.age = 20; john.gpa = 3.5; print_student_age_1(john); printf("gpa is %.1f\n", john.gpa); print_student_age_2(john_ptr); printf("gpa is %.1f\n", john.gpa); return 0; } void print_student_age_1(Student any){ printf("Age is %d\n", any.age); any.gpa = 2.0; } void print_student_age_2(Student * any){ printf("Age is %d\n", any->age); any->gpa = 2.0; } void print_student_age_3(const Student * any){ printf("Age is %d\n", any->age); any->gpa = 2.0; } john.agejohn.gpajohn_ptr 202000 20042008 3.5 any.ageany.gpa 20 40004008 3.52.0 any 2000 4000 2.0

6 Example 4: malloc and structs Student * many = (Student *)malloc(3 * sizeof(Student)); many[0].age = 20; many[0].gpa = 3.5; //void print_student_info( Student class [ ], int count ); OR //void print_student_info( Student * class, int count ); print_student_info(___________________, 3 ); many[0].agemany[0].gpamany[1].agemany[1].gpamany[2].agemany[2].gpa 233.4223.6214.0 800080048008801280168020 many 8000 2000


Download ppt "1 More on pointers. Example 1 – pass by value/reference int main(){ int p, q, r; p = 5; q = 6; r = Sum_1(p, q + 1); return 0; } void Sum_1(int a, int."

Similar presentations


Ads by Google