C-Kurs/StringArraySortieren/Musterlösung: Unterschied zwischen den Versionen
Mutax (Diskussion | Beiträge) K (hat „Ckurs2009/StringArraySortieren/Musterlösung“ nach „Ckurs/StringArraySortieren/Musterlösung“ verschoben: Aufgaben sind Kurs übergreifend nutzbar) |
Martin (Diskussion | Beiträge) (ML an neue Aufgabe angepasst) |
||
Zeile 1: | Zeile 1: | ||
− | + | <pre> | |
− | + | #include <stdio.h> | |
− | + | #include <stdlib.h> | |
− | + | ||
− | + | void mem_copy(char *dest, char *src, int len) { | |
− | + | int i; | |
− | + | for (i=0; i<len; i++) { | |
− | + | *dest++ = *src++; | |
− | + | } | |
− | + | } | |
− | + | ||
− | + | int str_compare(char *a, char *b) { | |
− | + | int diff; | |
− | + | ||
− | + | do { | |
− | + | char ca = *a++; | |
− | + | char cb = *b++; | |
− | + | ||
− | + | if ((ca == '\0') && (cb = '\0')) | |
− | + | return 0; | |
− | + | ||
− | + | diff = ca-cb; | |
− | + | } while (diff == 0); | |
− | + | ||
− | + | return diff; | |
− | + | } | |
− | + | ||
− | + | void sort(char **list, int length) { | |
− | + | int i, j; | |
− | + | for (i=0; i<length-1; i++) { | |
+ | for (j=0; j<length-i-1; j++) { | ||
+ | if (str_compare(list[j], list[j+1]) > 0) { | ||
+ | char *tmp = list[j]; | ||
+ | list[j] = list[j+1]; | ||
+ | list[j+1] = tmp; | ||
+ | } | ||
+ | } | ||
+ | } | ||
+ | } | ||
+ | |||
+ | int main(int argc, char *argv[]) { | ||
+ | char **list = malloc(argc * sizeof(char *)); | ||
+ | mem_copy((char*)list, (char*)argv, argc * sizeof(char *)); | ||
+ | sort(list, argc); | ||
+ | |||
+ | int i; | ||
+ | for (i=0; i<argc; i++) { | ||
+ | printf("%02d: %s\n", (i+1), list[i]); | ||
+ | } | ||
+ | |||
+ | return 0; | ||
+ | } | ||
+ | </pre> |
Version vom 17. September 2010, 18:37 Uhr
#include <stdio.h> #include <stdlib.h> void mem_copy(char *dest, char *src, int len) { int i; for (i=0; i<len; i++) { *dest++ = *src++; } } int str_compare(char *a, char *b) { int diff; do { char ca = *a++; char cb = *b++; if ((ca == '\0') && (cb = '\0')) return 0; diff = ca-cb; } while (diff == 0); return diff; } void sort(char **list, int length) { int i, j; for (i=0; i<length-1; i++) { for (j=0; j<length-i-1; j++) { if (str_compare(list[j], list[j+1]) > 0) { char *tmp = list[j]; list[j] = list[j+1]; list[j+1] = tmp; } } } } int main(int argc, char *argv[]) { char **list = malloc(argc * sizeof(char *)); mem_copy((char*)list, (char*)argv, argc * sizeof(char *)); sort(list, argc); int i; for (i=0; i<argc; i++) { printf("%02d: %s\n", (i+1), list[i]); } return 0; }