How to get the length of a char array?

2

How do I get the size of a set of char ( char** )? The way I'm trying is always returning me the value 4.

const char* opcSalgados[] = { "Pastel", "Mini pizza", "Coxinha", "Pao de queijo", "Pao de frango com queijo", "Pao de carne" };

void ImprimeMenu(const char** menuOpc)
{
    int Length = sizeof(menuOpc[0]) / sizeof(char); // Sempre me retorna o valor 4, deveria me retornar o valor o 6
    printf("Length: %i\n", Length);

    for (int i = 0; i < Length; i++)
        printf("%i - %s\n", i + 1, menuOpc[i]);
}
    
asked by anonymous 14.12.2017 / 16:45

2 answers

3

You can know the size of an array passed as an argument to a function using templates and type-deduction:

template <size_t N>
void imprimeMenu(const char *(&menuOpc)[N])
{
  int Length = N;
  printf("Length: %i\n", Length);

  for (int i = 0; i < Length; ++i)
    printf("%i - %s\n", i + 1, menuOpc[i]);
}

Notice how the parameter differs from yours:

template <size_t N>
void imprimeMenu(const char *(&menuOpc)[N])

In this case, we have a parameter menuOpc of type reference to an array of const char * fixed size N . When passing its array opcSalgados to the function (as shown below), this template will deduce parts of the parameter type that are known at compile time by the compiler.

imprimirMenu(opcSalgados);

So, given any% w of an array size, the type deduction will conclude that the M value needs to be equal to N , so that the template function instance is an appropriate candidate for the types of arguments.

You can simplify this code by using the std :: array container, which is effectively an array of fixed size, but with a better interface:

std::array<const char *, 6> opcSalgados = {
    "Pastel", "Mini pizza",
    "Coxinha", "Pao de queijo",
    "Pao de frango com queijo", "Pao de carne"
};

template <size_t N>
void imprimeMenu(std::array<const char *, N> menuOpc)
{ /* mesma implementação… */ }

The disadvantage of using M is that its size must be specified in the template parameter (as seen in code: std::array ). If your compiler supports C ++ 17, this problem goes away with the new deduction guides a>:

std::array opcSalgados = {
    "Pastel", "Mini pizza",
    "Coxinha", "Pao de queijo",
    "Pao de frango com queijo", "Pao de carne"
};

The std::array<const char *, 6> template parameters are automatically deducted by arguments passed to the constructor.

In any case, when you know the fixed size of the array (either a primitive array, or the std::array container), you can use the loop std::array

16.12.2017 / 02:51