Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

char* to char[]

Tags:

c++

I have char* which is of fixed (known) width but is not null terminated.

I want to pass it into LOG4CPLUS_ERROR("Bad string " << char_pointer); but as its not null terminated it will print it all.

Any suggestions of some light weight way of getting "(char[length])*char_pointer" without performing a copy?

like image 430
matt Avatar asked Apr 05 '11 12:04

matt


2 Answers

No, you'll have to deep-copy and null-terminate it. That code expects a null-terminated string and it means a contiguous block of characters ending with a null terminator.

like image 99
sharptooth Avatar answered Sep 29 '22 04:09

sharptooth


If your goal is to print such a string, you could:

  1. Store the last byte.
  2. Replace it with \0.
  3. Print the string.
  4. Print the stored byte.
  5. Put the stored byte back into the last position of the string.

Wrap all this in a function.

like image 42
Georg Schölly Avatar answered Sep 29 '22 04:09

Georg Schölly