C-Kurs/concat/Musterlösung: Unterschied zwischen den Versionen
(Die Seite wurde neu angelegt: „<pre> #include <stdio.h> #include <stdlib.h> int string_length(char* string) { int result = 0; while(string[result]!='\0') result++; return result; } char*…“) |
PaulG (Diskussion | Beiträge) K (verschob „Ckurs/concat/Musterlösung“ nach „C-Kurs/concat/Musterlösung“) |
||
(4 dazwischenliegende Versionen von 2 Benutzern werden nicht angezeigt) | |||
Zeile 13: | Zeile 13: | ||
char* concat(char *string1, char *string2) | char* concat(char *string1, char *string2) | ||
{ | { | ||
− | int len1 = | + | int len1 = string_length(string1); |
− | int len2 = | + | int len2 = string_length(string2); |
char* result = malloc(len1+1+len2+1); | char* result = malloc(len1+1+len2+1); | ||
int i; | int i; | ||
Zeile 34: | Zeile 34: | ||
{ | { | ||
char *current = concat(argv[1],argv[2]); | char *current = concat(argv[1],argv[2]); | ||
− | |||
char *result = current; | char *result = current; | ||
+ | int i; | ||
for(i=3; i<argc; i++) | for(i=3; i<argc; i++) | ||
{ | { | ||
Zeile 43: | Zeile 43: | ||
} | } | ||
printf("PARAMETER: %s\n",result); | printf("PARAMETER: %s\n",result); | ||
+ | return 0; | ||
}else{ | }else{ | ||
printf("Nicht genug Parameter"); | printf("Nicht genug Parameter"); | ||
+ | return -1; | ||
} | } | ||
} | } | ||
</pre> | </pre> |
Aktuelle Version vom 5. März 2013, 17:37 Uhr
#include <stdio.h> #include <stdlib.h> int string_length(char* string) { int result = 0; while(string[result]!='\0') result++; return result; } char* concat(char *string1, char *string2) { int len1 = string_length(string1); int len2 = string_length(string2); char* result = malloc(len1+1+len2+1); int i; for(i=0; i<len1; i++) result[i] = string1[i]; result[len1] = ' '; for(i=0;i<len2;i++) result[len1+i+1] = string2[i]; result[len1+1+len2] = '\0'; return result; } int main(int argc,char** argv) { printf("TEST: %s\n",concat("Wort1","Wort2")); //Zusatz if(argc>=3) { char *current = concat(argv[1],argv[2]); char *result = current; int i; for(i=3; i<argc; i++) { result = concat(current,argv[i]); free(current); current = result; } printf("PARAMETER: %s\n",result); return 0; }else{ printf("Nicht genug Parameter"); return -1; } }