char[32] as function parameter

Started by
12 comments, last by rip-off 8 years, 5 months ago

Just wrap a structure around it?


struct Char32 {
  char data[32];
};

void func(Char32 &param) { ... };
Advertisement
I would recommend using std::array to avoid all the messiness with decay to pointer. std::array is not like std::string, because it is a fixed size array that does not dynamically allocate memory.

As for std::array being owning, there are proposals to add array_view to the standard, which is a non owning range. This has the primary benefit of allowing the various ways that a sequence of objects are represented in c++ to converted to the same interface. But if you don't need a vector of 32 elements to be acceptable input then a reference to std::array<char, 32> is sufficient.

The syntax for array passing is crazy in C++ but this will do allow you to do this:

template <size_t charCount>
void stringCopy(char (&output)[charCount], const char* source)
{
}
I highly recommend you use a template on the array parameter here because this function now works with any sized arrays.

In this case the size is known, so you don't need the template:

void stringCopy(char (&output)[32], const char* source)
{
}
But I still recommend using std::array.

This goes a little bit off-topic, but I recently found this: https://docs.google.com/presentation/d/1h49gY3TSiayLMXYmRMaAEMl05FaJ-Z6jDOWOz3EsqqQ/preview?slide=id.gcfd0be4a_20

According to that, you should be able to statically enforce passed array sizes to have at least 32 entries by writing:


void func(char param[static 32])
{
}

However, I wasn't able to reproduce the compiler warning when passing an array with a smaller size. I'm using GCC 4.9.3 with these options:


gcc -W -Wall -Wextra -pedantic -o test main.c
"I would try to find halo source code by bungie best fps engine ever created, u see why call of duty loses speed due to its detail." -- GettingNifty

It appears to be a feature of C, not C++ (http://stackoverflow.com/questions/3430315/purpose-of-static-keyword-in-array-parameter-of-function)

This topic is closed to new replies.

Advertisement