Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Java to C – strings

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);
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

  • You will need arguments for the main function.
  • 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() and strcpy() 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);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading