Skip to content

Instantly share code, notes, and snippets.

@GGAlanSmithee
Last active October 21, 2021 13:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save GGAlanSmithee/825de2f24cc04083839ea1864d904a33 to your computer and use it in GitHub Desktop.
Save GGAlanSmithee/825de2f24cc04083839ea1864d904a33 to your computer and use it in GitHub Desktop.
simple C++ constant size array implementation

simple C++ constant size array implementation

Since you can only pass a pointer to an array - and not the array itself - as an argument to a function in C, the information regarding the length of the array is lost. While you can derrive the length with something like sizeof(arr) / sizeof(int), that is a run-time operation and quite ugly.

There are other data structures, such as std::vector, that solves this problem, but it comes with a lot of other aspects, such as dynamic memory allocation, that you might not be interested in.

This gist provides a super simple implementation of an array of a fixed size that is not dynamically allocated but has its length as a property. Just like a normal array, it allows indexed element read and write operations, but nothing more.

Considerations

I find this data structure useful as a substitute for the traditional C array, but like all things in programming, this implementation comes with its own set of drawbacks. The most obvious is that you have to specify the size of the array as a part of its type, which becomes a pain. In practise, what ends up happening is that you tend to have to annotate all functions that accepts an Array with the most generic template form, just like the struct itself:

template<typename T, size_t size>
void my_func(Array<T, size> & arr) {
  // ...
}

Also, because of how the operator[] is overloaded (returning a reference, which allows for write operations) you cannot create a const Array and expect indexed element access to work.

template<typename T, size_t size>
struct Array {
const int length = size;
inline T& operator[] (const size_t i) { return data[i]; }
private:
T data[size] = {};
};
#include <iostream>
template<typename T, size_t size>
void print(Array<T, size> arr) {
for (size_t i = 0; i < arr.length; ++i) {
std::cout << arr[i];
}
std::cout << std::endl;
}
#include "array.h"
int main()
{
Array<int, 10> int_arr;
Array<float, 20> float_arr;
Array<char, 30> char_arr;
print(int_arr); // prints "0" 10 times
print(float_arr); // prints "0" 20 times
print(char_arr); // prints " " 30 times
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment