Jook
Jook

Reputation: 4682

How to get the first x elements of a char array in C? Is there an improved way with boost-libraries?

My basic task is to get a subset of an buffer-array into another buffer array:

char buffer[max_len];

unit8 *pDestBuffer;

I used this code, because I would like to stay in ANSI-C:

memcpy(pDestBuffer, buffer, 4);

However - something must be wrong, because I don't get my result as I expect to. Because, when I debug buffer, I see all the slots of the array - when I do this with pDestBuffer, I get only one Item - which I can change however, with something like memset(pDestBuffer,1,4)

pDestBuffer is part of a structure, and the only other reference to it, besides the definition above, was were these lines:

requiredMemory = sizeof(Structure) + bufferSize;
pStructure = (Structure *)HostMalloc(requiredMemory);
pStructure->pDestBuffer = ((uint8 *)pStructure)+sizeof(Sturcture);

I know, this might be rather a basic task, and I am working on this myself, but please, if there is a "best-practice" for this or you know a solution, please share it with me.

As a twist, I would really like to know, if there might be an improved way for this, using the boost-libraries, which I do use anyways for other problems.

Upvotes: 1

Views: 3092

Answers (3)

CashCow
CashCow

Reputation: 31435

boost libraries is C++. Is this C or C++?

You say C in the title and your code is C but C++ is really a different language, with a different writing style.

What do you mean by "see all the slots"? If you are referring to Microsoft IDE, what you called unit8* which you probably mean uint8_t * or similar, is a pointer and it might interpret it as a null-terminated string but more likely just a pointer (due to its sign) and shows what it points to, rather than the start of an array.

Upvotes: 1

pmr
pmr

Reputation: 59811

I think "best practice" is not to mix C++ and C code.

#include <array>
#include <vector>
#include <algorithm>

std::array<char, len> buffer;
std::size_t n = 5;
std::vector<char> dest; // if n is dynamic
dest.reserve(n); // "performance"
std::copy(begin(buffer), buffer + n, std::back_inserter(dest));

// or even shorter
std::vector<char> dest{begin(buffer), buffer + n};

Upvotes: 2

john
john

Reputation: 8027

Your code is working. Just because your debugger cannot see the data doesn't mean it's not there. What's happening is that your code says uint8_t * pDestbuffer; so your debugger thinks that pDestBuffer is just a pointer to a single byte, so that's what it shows. You know however that it's actually a pointer to an array.

There may be some way of telling your debugger that this is an array so you can see all the data. For instance, one debugger I know would let you type in pStructure->pDestBuffer,4 to say show me four bytes not just one.

Upvotes: 4

Related Questions