views:

199

answers:

4

Hello,

i have a library which i have to pass (char **)&return_string to the function hci_scan as seen in this excerpt:

char return_string[250];
int num_hosts;

if ((num_hosts = hci_scan((char **) & return_string, 0x03)) > 0) {
    //case where one or more devices are found...
} else {
    //case where zero devices are found...
}

after this executes, what is in return_string? (so far all i have got is memory addresses)

thanks for you help

+4  A: 

The docs for hci_scan should tell you exactly what will come out of it, but my guess would be that it's going to be a string with the memory allocated from within hci_scan. You really shouldn't need to define return_string as an array; char *return_string; should work just as well.

womble
+3  A: 

If hci_scan modifies the value passed to it, as the use of a (char**) seems to imply, then your code is illegal, as you are not allowed to change the address of an array. I suspect hci_scan wants to allocate memory, so you want something like:

char * buf;
hci_scan( & buf );   // allocates string & points buff to it

but you really need to read the hci_scan docs to make sure.

anon
+1  A: 

It's wrong to cast char (*) [] to char **. Consider the follwing code:

char foo[42];
assert((void *)foo == (void *)&foo); // this will pass!

&foo is of type char (*) [42] and references the memory location of the array, which is the same location to which (char *)foo and &foo[0] point!

This means

char ** p = (char **)&foo;

is the same as

char ** p = (char **)foo;

which is nomally not what the programmer wants to do.

Christoph
A: 
char return_string[250];
int num_hosts;

if ((num_hosts = hci_scan((char **) & return_string, 0x03)) > 0) {
    //case where one or more devices are found...
} else {
    //case where zero devices are found...
}

Hm, what's the signature of hci_scan()? I mean what does it return? Even if you don't have access to the hci_scan() definition, you would still have the signature, assuming it's part of a third party api.

Looks like hci_scan() expects a pointer to a pointer so that it can allocate its own memory and return back the pointer. If that's indeed the case, you can do

char * return_string; /* No memory allocation for string */
int num_hosts;

if ((num_hosts = hci_scan(&return_string, 0x03)) > 0) { /* get back pointer to allocated memory */
    //case where one or more devices are found...
} else {
    //case where zero devices are found...
}

But then again it depends on what hci_scan is trying to do.

alok