How would you separately copy each line in a char array to an array of char arrays, in c?

Viewed 40

I am trying to put each line of a char array into separate char arrays. I am having a lot of unpredictable results and can't figure out where I'm messing up. Any help or criticism would be appreciated, thanks!

void TempControl::show_status_lines( const char *tmpc, int numlines )
{
    int len = strlen(tmpc);
    int line = 0;
    int j = 0;
    char tmpcstr[numlines][len];

    for ( int i = 0; i < len; i ++ ) {
        if ( tmpc[i] != '\n' ) {
            tmpcstr[line][j++] = tmpc[i];
        } else {
            line ++;
            j = 0;
        }
    }

    for ( int i = 0; i < numlines; i ++ ) {
        // show tmpcstr[i]...
    }
}

Please note: some code for drawing graphics was omitted for simplicity. I do not think any of it would be relevant here, but will include it if requested.

Edit: I got it working with the following code (with some extra modifications):

void TempControl::show_status( const char *tmpc )
{
    cairo_text_extents_t text;
    int len = strlen(tmpc);
    int line = 0;
    int j = 0;
    char tmpcstr[len];

    for ( int i = 0; i <= len; i ++ ) {
        if ( tmpc[i] != '\n' && i != len ) {
            tmpcstr[j++] = tmpc[i];
        } else {
            tmpcstr[j] = '\0';
            // show tmpcstr
            j = 0;
            line ++;
            tmpcstr[0] = '\0';
        }
    }
}

Thank you for the help!

0 Answers
Related