开发者

pointer problems?

开发者 https://www.devze.com 2023-04-08 02:05 出处:网络
buffer is a protected void* part of my class. void* ptr; ptr= buffer; if(ptr == pvTxt) return ptr; while (*((unsigned char*)ptr) || *(((unsigned char*)ptr)+1))

buffer is a protected void* part of my class.

void* ptr;
ptr= buffer;

if(ptr == pvTxt)
  return ptr; 

while (*((unsigned char*)ptr) || *(((unsigned char*)ptr)+1))
  ((unsigned char*)ptr)++;

return *((unsigned char*)ptr)+1;

Everything up to the:

((unsigned char*)ptr)++;

return *((unsigned char*)ptr)+1;

is fine but I know there is something wrong with the casting?

开发者_运维问答

Also in my main I have:

g_pvTxt = new unsigned char[BUFSIZE];  
memset (g_pvTxt,0,BUFSIZE);

Given the question above how do I append an array. Create an array/append to it. Can't use std::vector because it's an embedded system

To further explain the loop:

After an txt entry there is a null termination. At the end of all entries there is a double null. So, in the while loop if the value the pointer is pointing at is false (either 0 or 00) or ptr || ptr+1, it will increment the counter until it gets to the next spot where I can append values.


Why don't you just make the cast to unsigned char* only once?

unsigned char* ptr= static_cast<unsigned char*>(buffer);

if(ptr == pvTxt)
    return ptr; 

while (ptr[0] || ptr[1]) // *(ptr+1) would work as well
    ptr++;
return *ptr+1;

If you want to append to a buffer, and cannot use std::vector you can do something similar: allocate a bigger buffer, copy everything over and delete the old buffer.


I think you blew it before then.

if(ptr = Txt) is assigning Txt to ptr and then testing whether the value is null or not.

So the previous statement assigning ptr= buffer; has no effect.

And you'll never get past the first return so long as Txt has a value coming in.


Also be careful your scan or your response doesn't walk off the end of buffer.

I think you mistyped the variable names from your main example, but if you need to resize g_pvTxt you need to use "new" to get one of the newer size (current + append amount) then copy the two pieces to the new one manually, then discard the old array(s).

0

精彩评论

暂无评论...
验证码 换一张
取 消