dynmaic allocation

J

Jung, William

I have a function that convert a string to binary, where
- string is the string needs to convert to binary.
- binary is the BYTE array to hold the converted data

StringtoBinary( LPCSTR string, BYTE *binary)

Since BYTE is a pointer to BYTE, do I need to use new operator to
allocate space / storage (dynmaic allocation)?
 
M

maverik

I have a function that convert a string to binary, where
- string is the string needs to convert to binary.
- binary is the BYTE array to hold the converted data

StringtoBinary( LPCSTR string, BYTE *binary)

Since BYTE is a pointer to BYTE, do I need to use new operator to
allocate space / storage (dynmaic allocation)?

It depends. You can do it in several ways:

void
foo() {
BYTE binary[1234];
std::string str = "comp.lang.c++";

/* ... */
StringtoBinary(str, binary);
/* ... */
}

or if you don't know size of array

void
foo() {
std::string str = "comp.lang.c++";
BYTE binary = new BYTE[n];

/* ... */
StringtoBinary(str, binary);
/* ... */

delete[] binary;
}

or do it inside your function:

StringtoBinary(std::string str, BYTE *binary) {
binary = new BYTE[n];

/* ... */
}

but I think it's not a good idea.
 
M

maverik

    BYTE binary = new BYTE[n];

I mean BYTE *binary = new BYTE[n];
StringtoBinary(std::string str, BYTE *binary) {
    binary = new BYTE[n];

    /* ... */

}

but I think it's not a good idea.

Because in this case you cannot use binary outside of StringtoBinary
(). If you really need this you should give a pointer-to-pointer as an
argument:


StringtoBinary(std::string str, BYTE **binary) {
*binary = new BYTE[n];

/* ... */
}
 
J

James Kanze

I have a function that convert a string to binary, where
- string is the string needs to convert to binary.
- binary is the BYTE array to hold the converted data
StringtoBinary( LPCSTR string, BYTE *binary)
Since BYTE is a pointer to BYTE, do I need to use new operator
to allocate space / storage (dynmaic allocation)?

If you do, there's no way you can pass it back to the user.

But this interface is completely broken anyway, and can't be
made to work. The simplest would be to change it to something
like:
std::vector< BYTE > StringToBinary( std::string string ) ;
..
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,766
Messages
2,569,569
Members
45,042
Latest member
icassiem

Latest Threads

Top