Rudi-peto asked:
But anyway, I store each hex into buffer... But how do I store it to array of pointer, so it looks like: …
Please see my comments to Solution 1.
You really need to get comfortable with pointers and arrays, that's it. Let me show one very simple and memory-efficient approach. Let's say, you input buffer of bytes you called buff in the question has the length
count
:
int count = strlen(buff);
Before you proceed, you have to allocate the buffer for output string, call it
output
. Instead of allocating each string separately and using some pointers to an array of pointers ("jagged array"), let's simply put then all in one buffer. How much memory you need? Each hexadecimal string will take 4 bytes, if we count 'x': also two half-byte hexadecimal digits and null, because we are messing up with those stupid null-terminated strings. So, for whole output buffer, you will need just
count*4
bytes:
char * output = new char[count * 4];
delete[] output;
In the loop, you can call
sprintf
(Solution 1)
count
times. Let's do simple "manual" pointer arithmetic. First string passed as the first
sprintf
call will be at the very end of the buffer, so the pointer would be the same as
output
. To get the pointer to next string, increment this pointer adding exactly 4. As the
compile-time type of the element of the array
output
is 1-byte
char
, the compiler will interpret this 4 as 4 bytes. So, in each loop iteration, the string pointer for each string will be equal to
output + 4 * index
, where
index
is the
loop control variable. This way, you will populate the array with
count
strings of the same length.
Essentially, I wrote the complete pseudo-code for you. You populate all the output hex string in the loop. Later on, you can use this
output
array to access any of these string by index, using exactly the same pointer arithmetic.
Alternatively, you can also use "2D" arrays, as explained here, understanding that in C++ "2D" is just a
metaphor, the way to interpret the same pointer:
http://www.cplusplus.com/doc/tutorial/arrays[
^].
Also note that the term "2D", "3D" and so one is nothing but some jargon. Mathematically correct work is "rank". In the strict mathematical terminology, all those finite sets are always zero-dimensional objects. Only continuums can have such property as "dimension". From elementary linear algebra and analytical geometry, you can learn that continuous linear spaces can have some integer dimensions. And the geometrical object can have dimensions of 1, 2, 3 and more if they are the manifolds in some continuous spaces; for other geometrical objects, the dimension can be fractional or at all undefined. But this is a different story…
—SA