Arm Mbed OS support forum

How to change char array properly

Hello,

I’m trying to modify char array and noticed big problem with adding next chars to array. After 4 operations I can’t add next chars to the array. Here is the code.

The output is:
c
cc
ccc
cccc
cccc
cccc
cccc
cccc
cccc
cccc

insted of:
c
cc
ccc
cccc
ccccc
cccccc
ccccccc
cccccccc
ccccccccc
cccccccccc

Can you help me to find where is the problem with code?

Best regards
Maciek

Code:

#include "mbed.h"

// SERIAL PINS
static BufferedSerial dbg ( PA_9 , NC , 115200 ) ;

// main() runs in its own thread in the OS
int main()
{
    //DBG configuration
    dbg.set_format( 8 , BufferedSerial::None , 1 ) ;

    char* p = new char[10] ;
    char c = 'c' ;

    for ( int i = 0 ; i < 10 ; i++ )
    {
        p [ i ] = c ;
        p [ i + 1 ] = '\0' ;
    
        dbg.write ( "\r\n" , sizeof ( "\r\n" ) ) ;
        dbg.write ( p , sizeof ( p ) ) ;    

    }
}

I think this is what you want.

// char* p = new char[10] ;
char p[11] = {0};

Yes, it’s working now. However You inspired me and I’ve try this:

//dbg.write ( p , sizeof ( p ) ) ;
dbg.write ( p , strlen ( p ) ) ;
and it works with this:
char* p = new char[11] ;

Thank you very much and best regards
Maciek