Sunday, October 26, 2014

Copying non null-terminated char array to String

Sometimes while listening to data on a network, the packet structure defined contains data members of type char[]. In most of the cases, the data in these char[] data members  will not be null terminated.


structObj.charArray[8] = { 'p', 'a', 'r', 'a', 'g', ' ', ' ', ' ' };  
//see all 8 chars occupied, with no null termination at the end. 

 How do you read the object in your program. There are various ways, here's one:

#include <iostream>
#include <string>
#include <cassert>

#define ARRAY_SIZE(a) sizeof(a)/sizeof(a[0])
int main()
    char input[MAX_INPUT_ARR_SIZE] = { 'p', 'a', 'r', 'a', 'g' };
    const std::string output( input, ARRAY_SIZE(input) );
    std::cout << output << std::endl;
    //To check on the size 
    assert(output.length() == MAX_INPUT_ARR_SIZE);
    return 0;


No comments:

[Solved] Android Studio : Android emulator is incompatible with Hyper-V

Have been lately doing Android development. Ran into a minor problem. So I have two machines, a desktop and a laptop. I set the project on ...