Embedded Basics – A few Array Misconceptions


RSS
Follow by Email
Facebook
Facebook
Google+
Google+
http://beningo.com/embedded-basics/
YouTube
LinkedIn

Arrays are one of the most widely used data objects in C, yet, as it would turn out there are a number of misconceptions about arrays and a few tricks that are completely misunderstood or unknown to most programmers!

Misconception

Take for example a simple initialization of an array so that each element is decimal 20:

int MyArray[5] = { 20 };

Many programmers would expect this to be the equivalent of

int MyArray[5] = {20, 20, 20, 20, 20 };

Unfortunately this is NOT the case!  It is actually the equivalent of

int MyArray[5] = {20, 0, 0, 0, 0];

The misconception arises from the fact that it is common to initialize to 0 where we see

int MyArray[5] = {0};

This statement will initialize each element to 0!  Don’t forget that global and static variables will be automatically initialized to 0 by the compiler as seen below:

int MyArray[5];                /* initialized to 0, 0, 0, 0, 0 Note extern is implicit! */

static in MyArray[5];        /* initialized to 0, 0, 0, 0, 0 */

Another interesting fact is that as most developers know is that you can’t assign one array to another.  For example, the following would result in a compiler error:

int MyArray[2] = { 2, 3};

int YourArray[2] = {0};

YourArray = MyArray;

What most developers don’t realize is that there IS a way to do this!  It can be done using a struct!  For example a wrapper struct can be created as follows:

typedef struct

{

int MyArray[2];

}ArrayWrapper;

The struct’s can then be initialized and the array set by using the following:

ArrayWrapper Wrapper1;

ArrayWrapper Wrapper2;

Wrapper1.MyArray[0] = 15;

Wrapper2 = Wrapper1;

After executing the code Wrapper2.MyArray will have the same contents as Wrapper1.MyArray!  A neat trick that isn’t used terribly often but is still useful to know!

 

RSS
Follow by Email
Facebook
Facebook
Google+
Google+
http://beningo.com/embedded-basics/
YouTube
LinkedIn

Leave a Reply

Your email address will not be published. Required fields are marked *