I have to "convert" java to c. Did I do it right? Can you correct
public static void main(String[] args) {
String s = args[0];
String t = args[1];
String st = s + t;
}
Java -> C
int main() {
char *s = args[0];
char *t = args[1];
char *st = (char*) calloc(1, strlen(s) + strlen(t) + 1); // '\0' nicht vergessen!
strcat(st, s);
strcat(st, t);
free(st);
}
>Solution :
- You will need arguments for the
mainfunction. - The first argument in C will corresponds to the executable itself. Therefore, you should start working with second argument.
- Casting results of
malloc()family is considered as a bad practice. - You can use
malloc()andstrcpy()to save initialization. - It will be safer to check for preconditions in C because it won’t check for them and safely throw exceptions like Java.
#include <stdlib.h>
#include <string.h>
int main(int argc, char* args[]) {
if (argc < 3) return 1; // check if there are enough arguments
char *s = args[1];
char *t = args[2];
char *st = malloc(strlen(s) + strlen(t) + 1); // '\0' nicht vergessen!
if (st == NULL) return 1; // check if allocation succeeded
strcpy(st, s);
strcat(st, t);
free(st);
}