Ad

Should I Expect A Char** Or A Char* Here From The Caller?

- 1 answer

I have a function which accepts a pointer to some data, along with an enum representing the type of the data (lets call it processData). processData takes the data and, depending on the enum, does stuff with it (I have simplified the types here for example sake):

typedef enum
{
  Integer, Double, String
} DataType;

void processData(void* data, DataType type)
{
  // Do stuff with data (not necessarily modifying it like I have here,
  // but it does requires the data to be passed by pointer, and not by value)
  if (type == Integer)
  {
    (*(int*)data)++;
  }
}

Excluding the fact that this example is a bit weird, my question is, would it make sense to ask the caller to pass through a char* directly and then not de-reference it in my function like the other cases, or to pass through a char** and then de-reference it on my side to get a char* and deal with it from there?

Of course, both are possible - I am just asking which would be more intuitive in this sort of situation, and maybe if there are similar situations I can be referred to for reference sake.

Ad

Answer

In this case I don't think you need to pass a string as char ** because the extra layer of abstraction is not necessary, this might be confusing. I would suggest pass other types as pointers as well.

e.g.

  • Input is a string -> pass char *

  • Input is a 16 bit value -> pass uint16_t * and deference it in processData

Depending on what you're doing with the string, it might make sense to pass a length as well unless you're searching for "\0" every time processData is called on a string.

Ad
source: stackoverflow.com
Ad