Search code examples
arrayscstringdynamicchar

How can I make char string array in C have dynamic size?


C language I'm writing a function that relies later on on generating some text that has to hold the length of essentially: 115 letters minus the length of substring within <> from the original argument to the function - (115 - substring length).

However, C doesn't accept char text[value] with dynamic value, and I need it in that code to be dynamic and dependent on how large the size of extracted substring was.

How can I do that?

char* RandomText(char* originalMsg)
{
    char* subString;
    char msgClone[256];
    strcpy(msgClone, originalMsg);
    subString = strtok(msgClone, "<");
    subString = strtok(NULL, ">"); 

    int spewageSize = 115 - strlen(subString); //110 + safe buffer for \n and \0

    char text[spewageSize]; 

    // the rest of the code follows here
}

Solution

  • How can I do that?

    Do not write code that assumes small string lengths.
    Negate the need for char msgClone[256]; and strtok().
    Allocate memory.

    1. Use strcspn() to find the offset of the "<" and ">".
    //                   v---v note the const
    char* RandomText_Alt(const char* originalMsg) {
        size_t open_offset = strcspn(originalMsg, "<");
        const char *substring = &originalMsg[open_offset];
        if (*substring) substring++;
    
        size_t close_offset = strcspn(substring, ">"); 
    
        // Limit sub-string length if desired.
        if (close_offset >= 115) {
          close_offset = 115 - 1;
        }
    
        char *text = malloc(close_offset + 1);
        if (text) {
          memcpy(text, substring, close_offset);
          text[close_offset] = '\0';
    
          // The rest of the code follows here.
    
          free(text);
        }
    ...