C-Kurs/(Pointer) Swapping/Musterlösung: Unterschied zwischen den Versionen
< C-Kurs | (Pointer) Swapping
Zeile 1: | Zeile 1: | ||
+ | 1. Teilaufgabe | ||
+ | |||
#include <stdio.h> | #include <stdio.h> | ||
Zeile 21: | Zeile 23: | ||
printf("i: %i j: %i\n", i, j); | printf("i: %i j: %i\n", i, j); | ||
+ | } | ||
+ | |||
+ | |||
+ | 2. Teilaufgabe | ||
+ | |||
+ | #include <stdio.h> | ||
+ | |||
+ | |||
+ | void swap(int *x, int *y) { | ||
+ | |||
+ | int t = *x; | ||
+ | *x = *y; | ||
+ | *y = t; | ||
+ | } | ||
+ | |||
+ | void print_int_array(char* name, int* array, int size){ | ||
+ | |||
+ | int i; | ||
+ | |||
+ | printf("%s:", name); | ||
+ | for(i= 0; i<size; i++) | ||
+ | printf(" %i", array[i]); | ||
+ | printf("\n"); | ||
+ | } | ||
+ | |||
+ | int main(){ | ||
+ | |||
+ | |||
+ | int a[]= {1, 2, 3, 4}; | ||
+ | int b[]= {5, 6, 7, 8}; | ||
+ | |||
+ | print_int_array("a", a, sizeof(a)/sizeof(int)); | ||
+ | print_int_array("b", b, sizeof(b)/sizeof(int)); | ||
+ | |||
+ | int i; | ||
+ | for(i=0; i<4; i++) | ||
+ | swap(&a[i], &b[i]); | ||
+ | |||
+ | print_int_array("a", a, sizeof(a)/sizeof(int)); | ||
+ | print_int_array("b", b, sizeof(b)/sizeof(int)); | ||
} | } |
Version vom 24. September 2009, 08:58 Uhr
1. Teilaufgabe
#include <stdio.h> void swap(int *x, int *y) { int t = *x; *x = *y; *y = t; } int main(){ int i= 1; int j= 2; printf("i: %i j: %i\n", i, j); swap(&i, &j); printf("i: %i j: %i\n", i, j); }
2. Teilaufgabe
#include <stdio.h> void swap(int *x, int *y) { int t = *x; *x = *y; *y = t; } void print_int_array(char* name, int* array, int size){ int i; printf("%s:", name); for(i= 0; i<size; i++) printf(" %i", array[i]); printf("\n"); } int main(){ int a[]= {1, 2, 3, 4}; int b[]= {5, 6, 7, 8}; print_int_array("a", a, sizeof(a)/sizeof(int)); print_int_array("b", b, sizeof(b)/sizeof(int)); int i; for(i=0; i<4; i++) swap(&a[i], &b[i]); print_int_array("a", a, sizeof(a)/sizeof(int)); print_int_array("b", b, sizeof(b)/sizeof(int)); }