Search code examples
cprintfsubstringc-stringsconversion-specifier

How to create a char* substring of a char* string in C?


I want to create a substring, which I see online everywhere and it makes sense. However, is there any way to, instead of outputting to a regular array of characters, output the substring as a char* array?

This is the idea of my code:

char *str = "ABCDEF";
char *subStr = calloc(3, sizeof(char));
memcpy(subStr, &str[3], 3);
fprintf(log, "Substring: %s", subStr);

I am hoping this will print out DEF. Let me know what you guys think I should do, or if this will work. Thanks!


Solution

  • You have to terminate the string by adding terminating null-character.

    const char *str = "ABCDEF"; /* use const char* for constant string */
    char *subStr = calloc(3 + 1, sizeof(char)); /* allocate one more element */
    memcpy(subStr, &str[3], 3);
    fprintf(log, "Substring: %s", subStr);
    

    calloc() will zero-clear the buffer, so no explicit terminating null-character is written here.