Embedded Basics – A few Array Misconceptions
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!
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!
Struggling to keep your development skills up to date or facing outdated processes that slow down your team, raise costs, and impact product quality?
Here are 4 ways I can help you:
- Embedded Software Academy: Enhance your skills, streamline your processes, and elevate your architecture. Join my academy for on-demand, hands-on workshops and cutting-edge development resources designed to transform your career and keep you ahead of the curve.
- Consulting Services: Get personalized, expert guidance to streamline your development processes, boost efficiency, and achieve your project goals faster. Partner with us to unlock your team's full potential and drive innovation, ensuring your projects success.
- Team Training and Development: Empower your team with the latest best practices in embedded software. Our expert-led training sessions will equip your team with the skills and knowledge to excel, innovate, and drive your projects to success.
- Customized Design Solutions: Get design and development assistance to enhance efficiency, ensure robust testing, and streamline your development pipeline, driving your projects success.
Take action today to upgrade your skills, optimize your team, and achieve success.
