Two ways to initialize an array in C

I don’t often post about C, but I’ve been programming a lot in the Arduino world recently, and thought I’d post a quick couple of tips on a small programming challenge I encountered.

I needed to declare a character array (of length 64) – this is pretty simple.

char radioTextData[64];

And when I write the contents of this array to the Serial output…

for (short i = 0; i < sizeof(radioTextData); i++) {

…instead of seeing blank values, I see character values which were previously in the memory location used by my array variable.

So how can I make this array initially empty?

The hard way – write a function to loop over the array

As a .NET developer, this seemed like it should be pretty easy to me – in .NET variables are passed by reference so I can just pass the array into a method, and iterate over the array to set each value to whatever I want it to be (or use clever framework methods).

But when programming in C for the Arduino, it’s a little more complex to clear an array using a loop in a separate function. First we have to set up a pointer to the original array.

char radioTextData[64];
char* pointerToRadioTextData = radioTextData;

And now we have a pointer to the array, we can pass that to a function to process it – we also need to pass the size of the array because we can’t work that out from the pointer to the original array.

void clearArray(char* myArray, short sizeOfMyArray) {
    for (short i = 0; i < sizeOfMyArray; i++)
        myArray[i] = ' ';

The easy way – use memset

memset allows us to initialise an array to a specified character – so using just one line of code I can achieve the same result as in the first part of this post by passing the array, the size of the array, and the character that each element of the array to be initialised to.

memset(radioTextData, ' ', sizeof(radioTextData));

Summing up

So obviously to initialize and array, my code will use the easy way – it’s short, clear and elegant. But the technique of processing an array in C by passing a pointer to the start of the array is useful too.

3 thoughts on “Two ways to initialize an array in C

  1. Why the need for pointerToRadioTextData?
    It’s been a while since I coded in C, but I’m pretty sure

    clearArray(radioTextData, sizeof(radioTextData));

    will work just fine without the intermediate step.

    1. Thank you James – this is a really good tip. I’ll test and if it works with Arduino I’ll update the article title to be three different ways to initialise an array (and give you credit of course).

Comments are closed.