简体   繁体   中英

Returning string from function having multiple NULL '\0' in C++

I am compressing string. And the compressed string sometimes having NULL character inside before the end NULL. I want to return the string till the end null.But the compressor function is returning the sting till the occurring of the first NULL. I made a question for c before about it. But consecutively I need also the solution in C++ now, and in next C#. Please help me.Thanks.

char* compressor(char* str)
    {
      char *compressed_string;
      //After some calculation
      compressed_string="bk`NULL`dk";// at the last here is automatic  an NULL we all know
    return compressed_string;
    }
void main()
   {
    char* str;
    str=compressor("Muhammad Ashikuzzaman");
    printf("Compressed Value = %s",str);

   }

The output is : Compressed Value = bk; And all other characters from compressor function is not here. Is there any way to show all the string.

The fundamental problem that you have is that compression algorithms operate on binary data rather than text. If you compress something, then expect some of the compressed bytes to be zero. Thus the compressed data cannot be stored in a null-terminated string.

You need to change your mindset to work with binary data.

To compress do the following:

  1. Convert from text to binary using some well-defined encoding. For instance, UTF-8. This will yield an array of unsigned char .
  2. Compress the unsigned char , which will again yield an array of unsigned char , but now compressed.

To decompress you just reverse these steps.

Since you are writing C++ code you would be well advised to use standard containers. Such as std::string or std::wstring and std::vector<T> .

The exact same principles apply in all languages. When you come to code this in C#, you need to convert from text to binary. Use Encoding.GetBytes() to do that. That yields a byte array, byte[] . Compress that to another byte array. And so on.

But you really must first overcome this desire to attempt to store binary data in text data types.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM