Home > OS >  How to know the last element of a byte pointer?
How to know the last element of a byte pointer?

Time:01-22

I need to know what the last byte of this pointer is.

NULL, 0, nullptr, '\0'... does not work.

#include <iostream>
#include <iterator>
//------------------------------------------------------------------
struct MyStruct
{
    int myNumber;
    char c[10];
    std::string s;
};
//------------------------------------------------------------------
int GetSize(char *data)
{
    char* ptr = data;
    int size = 0;

    for (char* it = ptr; it!= nullptr; it  , size  )//<-- it does not work
    {
        std::cout << "size-->" << size << std::endl;
    }

    return size;
}
//------------------------------------------------------------------
int main()
{
    MyStruct data;

    std::cout << "size-->" << sizeof(MyStruct) << std::endl;
    std::cout << "size-->" << sizeof(data) << std::endl;
    system("pause");    
    

    GetSize((char*)&data);
}
//------------------------------------------------------------------

Is there any way to do it?

The code has been extended by community request.

CodePudding user response:

If this was just to exercise then the lesson to learn is: No. It does not work like that.

You can cast the pointer to MyStruct to a pointer to char and you can inspect the bytes via that pointer. So far so good. However, there is no way to know the size of MyStruct given only that char*.

You already know the size of MyStruct it is sizeof(MyStruct). You could write the loop like this:

for (int i=0; i< sizeof(MyStruct);   i,  data)
{
    std::cout << static_cast<unsigned>(*data) << std::endl;
}

This way you can read the data as if it was a stream of bytes.

The pointer data will never equal nullptr or 0 or \0 by incrementing it. With some luck the byte it points to, *data, might equal 0, but it will not be at the end of the object.

You cannot determine the size of MyStruct given only a char* pointing to an instance.


For your question literally:

How to know the last element of a byte pointer?

You can see what the last byte is via data[ sizeof(MyStruct) -1] (when printing you might want to cast to unsigned as above, because otherwise it will be printed as character, possibly non-printable).

  •  Tags:  
  • c
  • Related