Use of union in C in place of structure will save memory?

The structure can not be replaced by a union in an application, just bear that in your mind. Both are two different things and are used in different scenarios. It is the basic thing that both structure and union can have some number of elements inside them. But their uses are quite different from each other depending on the information required to be contained.

The structure (keyword: struct in C) has some elements and all the elements of the structure shall reserve memory for them.

Here you see that we have declared a struct witch has two elements in it: 1- name (char array of size 20; occupy 20 bytes in memory) and 2- phone (integer array of size 12; occupy 4*12 = 48 bytes). This structure shall hold total 20 + 48 = 68 bytes in memory whenever we use a variable of this structure type. It can have both name and phone details and both are mandatory to store contact details in an application.

Lets take a case where any of these two attributes (name and phone) is enough for the contact detail, then also would it be good idea to hold 68 bytes in memory ? Then answer is NO, use a union my friend.

In case of union, among its various elements, element which is largest in size would cause to hold only that much memory. Here in our case, name is of 20 bytes and phone of 48, so memory equal to 48 bytes will be reserved for this union type variable.

Here we need to understand again that only one element of the union can have the information, not all. So the programmer has to decide on the need for a specific application.



How to reset / unset a particular bit in a byte

In our previous post “How to set a particular bit in a byte” had a solution with ‘|’ (OR) bit operator. Now to reset a particular bit in a word, we will see use of some more bit operators like, ~(NOT) and &(AND). Have a look on the following solution with a macro:


Be careful with the inappropriate use of the parenthesis with macro declaration.

Can const and volatile qualifiers be used at the same time in C?

In real time systems we can find a use where both const and volatile qualifiers are used for a single variable. Before going to know about there simultaneous usage we need to understand both the qualifiers separately.

When we talk about ‘const’, what is the first thing that comes to our mind?

const keyword gives a condition that it can not be changed during the life time of the program, e.g.

Here the value of pi (it’s a float constant here) can not be changed during execution of program. Here the important note is ‘pi’ is such a value that must not be changes in any scenario of any calculations, if tried to change it by any operation an error shall be thrown.

Lets now talk about ‘volatile’ keyword. Earlier when we declare ‘pi’ as a constant, the compile was told that it’s value would not be changed so compiler can optimize in a way where pi value can be referenced directly without checking whether it’s value is updated in any of the operations recently (because it is a const value). Here we need to understand that compiler optimizes a lot of thing with it’s intelligence without knowledge of user to save CPU cycles during various operations. The scenario will be just opposite if ‘volatile’ is used, e.g.

Here the temperature is the variable that can be changed at any time and thus whenever it’s value is referenced it is required that it’s recent updated value must be referenced. So it’s a direction to compiler that the ‘temperature’ value is so sensitive to change and must not be optimized by the compiler in a way that it’s latest updated value is missed in any operation. So such variables are not stored in the cache memory for quick reference by the compiler.

Now take a case when both volatile and constant can be used all together. e.g.

This is a valid case and where is it use? This combo is used in the embedded systems to access the registers (like status registers) which are updated by hardware like hardware interrupt, but change is not expected from any software operation.


How to set a particular bit in a byte

This question is the basic one when you face a embedded domain interview. If you can not answer this, interviewer may loose his faith in your low level C programming skills.

This question becomes more critical when it is asked to give the solution with a macro. Have a look on it’s implementation below:

Here the bit operator ‘|’ called OR has the property to set a bit irrespective of other operand if one operand is 1. Recall OR gate truth table from Digital Electronics for more fun on this.

How to find that system/processor supports little endian or big endian representation

First it is important to know that what are little endian and big endian  representations. It can be understood by the storage of the byte of a word in the conjugate memory location.

Big Endian: Store the bytes (from left to right) of a word in incremented (BIG) memory location. 0x0A0B0C0D => memory location 0x100 shall hold 0A, 101(0B), 102(oC) and 103(oD).

Little Endian: Store the bytes (from left to right) of a word in decremented (LITTLE) memory location. 0x0A0B0C0D => memory location 0x100 shall hold 0D, 101(0C), 102(oB) and 103(oA).

The output of above program shall depend on the processor on which it is run. Here we are trying to know that where exactly the 01 of 0x00000001 (HEX representation of ‘1’ if int is 4 byte) is stored in the memory. Pointer typecast is the key of this solution. If you are not very clear about pointer typecasting then first refer some text on that.


How to find the number of set bits in a byte or word

Lets assume a byte: 0110 0111

Method-1: This simplest way to get the count of set bit ‘1’ is to run a loop for the length (in bits) and check if the LSB  is ‘1’ and increment the counter and shift the byte by one position left. At the end of loop the counter value shall hold the desired count of set bit.

It takes the iteration equal to total no of bits in the byte/word, Time Complexity: O(n).

Method-2: Another method that easily could be memorized as AND method, will give a save on no of iterations.

In the second method, the while loop iteration shall run only equal to the number of the 1’s in the word, so this method is more optimized than previous one in terms of time complexity.

Hint: Logic behind this method can be understood by (num & num-1) shall remove the most right side ‘1’ from the target number. Rest is left for your imagination.

If you know any other better solution than this, then please post your answer in the comment area below.

Find Maximum Difference between two elements of an Array

Maximum difference between two elements such that larger element appears after the smaller number

For example if we have array as 10, 7, 2, 5, 6, 8, 9, 5, 3

Maximum difference Array[j] and Array[i] is 7 between Array[6] and Array[2]

Condition is that “j” should be greater than “i”

Time Complexity: O(n)

If you know any other better solution than this, then please post your answer in the comment area below.

Find the Number that Appears Only once in an array of Duplicates

We have an array with various duplicate numbers but one number is there which appears only single time. We need to find that number with minimum time complexity

XORing  all elements of an array will give the output

Time Complexity: O(n)

Space Complexity: O(1)

If you know any better solution than this then please post it into below comment area.

Merge 2 Arrays without using Extra Space

We have two sorted arrays. Second array has sufficient space for merging first and second array elements. Without using additional space (memory) merge two arrays

Input Array1: 1,  20,  25,  35,  40

Input Array2: 5,  15,  30,  45,  50,  _,  _, _, _

Output: Array2 = 1,  5,  15,  20,  25,  30,  35,  40,  45,  50

Here we two arrays which are sorted in ascending order. In Array2, we have sufficient space to add elements of Array1.

Complexity: O(n+m)

Algorithm: We will start inserting largest element from the end.

Take two variable pointing last non empty element of two arrays. So “i” pointing to 20 and “j” pointing to 21

Now insert the greatest number at the end of second array

For example if Array2[j] > Array1[i] then insert Array2[j], i.e 21 at the end of Array2 and decrement “j”

Similarly proceed till “i” or “j” is not equal to -1

Below is the working code for the above problem where n and m are the number of elements in Array1 and Array2 respectively.

If you know any better solution than this, then please post it in below comment’s area.

Arrange smaller numbers before the key and greater after the key

Given an array of numbers and a Key value. Arrange it in such a way that all the numbers less than a given key should come before the key and all the numbers greater than the key should come after it.

Input:  0,  3,  -2,  2,  0,  -1,  5

Key: 0

Output:  -1,  -2,  0,  0,  2,  3,  5


Take the key and search from start of array and count how many numbers are greater than and equal to the key value. Also save the position (index of array) where you have found the key in the array.

In above example loop through and count numbers greater than 0 (key) and also find the first location of the key in array

We found

key position (index) let Y = 0

Number of items greater than equal to the key value let X = 5

Length of array let L

Now we will swap the A[L – X] and A[Y] and now the array becomes

-2,  3,  0,  2,  0,  -1,  5

Now take variable i and j, i pointing to A[0] and j pointing to Y+1 (just after first occurrence of key) as shown in figure below.

arrange numbers less than key on left and greater on right


If you know any other better solution than this, then please post your answer in the comment area below.

Page 1 of 3123