🚀 Learn BLE on Linux (BlueZ) – Programming Part 1
Hands-on Bluetooth Low Energy course. Special price: ₹399
Enroll Now on Udemy →Free C Programming Course · Structure and Union
Arrays Inside Structures in C
Put arrays inside structures, copy them by value, build a small FIFO, then test yourself with a quiz and interview questions.
What You Will Learn
- How to declare and access arrays that are members of a structure
- Why assignment copies the embedded array
- How to build a small FIFO structure for embedded code
- Quiz, output prediction and interview questions on the whole structures topic
Prerequisites
- Array of structures (previous lecture)
- Structure assignment and padding
Arrays Inside Structures in C
Arrays inside structures in C let one record carry a list of values: a student with four subject marks, a packet with a payload buffer, a ring buffer with its storage. Until now our structure members were single values or a name string. Here we put a real array inside the structure and see how it behaves when you index it, copy it and pass it around. This is the last lecture on this part of the free embedded C course, so it ends with a quiz and interview questions.
Declaring and Accessing an Array Member
#define SUBJECTS 4
struct result {
char name[16];
int roll;
int marks[SUBJECTS];
};
The structure has two array members: name (16 characters) and marks (4 integers). Access rules combine the tools you already know:
| Expression | Meaning |
|---|---|
r.marks[0] | First mark of the structure variable r |
r.name[0] | First character of the name |
batch[2].marks[3] | Fourth mark of the third element of an array of structures |
batch[2].name[0] | First character of the third student’s name |
p->marks[1] | Second mark through a pointer p to the structure |
Read from left to right: pick the element, pick the member, then pick the position inside the array member. Each step is one operator.
The array member sits inside the structure’s own block, in place. There is no separate allocation and no pointer: marks really is 16 bytes inside the record. Offsets 0, 16 and 20 are all suitable for their types, so this layout needs no padding.
Example: Student Marks Table
This program builds an array of three records, each holding an array of marks, then computes totals and averages with a helper that takes a pointer. It also copies one record to show that the embedded array is copied by value.
#include <stdio.h>
#define SUBJECTS 4
struct result {
char name[16];
int roll;
int marks[SUBJECTS];
};
static int total(const struct result *r)
{
int t = 0, j;
for (j = 0; j < SUBJECTS; j++)
t += r->marks[j];
return t;
}
int main(void)
{
struct result batch[3] = {
{ "Asha", 1, { 80, 75, 90, 85 } },
{ "Ravi", 2, { 60, 70, 65, 72 } },
{ "Meena", 3, { 95, 88, 92, 91 } },
};
struct result copy = batch[1];
int i;
for (i = 0; i < 3; i++)
printf("%-6s roll=%d total=%d avg=%.2f\n",
batch[i].name, batch[i].roll, total(&batch[i]), total(&batch[i]) / (float)SUBJECTS);
copy.marks[0] = 0;
printf("batch[1].marks[0] = %d, copy.marks[0] = %d\n", batch[1].marks[0], copy.marks[0]);
printf("batch[2].name[0] = %c, batch[0].marks[3] = %d\n", batch[2].name[0], batch[0].marks[3]);
return 0;
}
gcc -std=c11 -Wall -Wextra -o e1 e1.c
./e1
Expected output:
Asha roll=1 total=330 avg=82.50
Ravi roll=2 total=267 avg=66.75
Meena roll=3 total=366 avg=91.50
batch[1].marks[0] = 60, copy.marks[0] = 0
batch[2].name[0] = M, batch[0].marks[3] = 85
The fourth line is the important one. After copy = batch[1] we zeroed copy.marks[0], yet batch[1].marks[0] still reads 60. The whole array travelled with the structure, so the copy owns its own marks. This is a quiet superpower of arrays inside structures: you can wrap a fixed-size array in a structure purely to make it assignable and passable by value, something a bare array cannot do.
Embedded Example: A Tiny FIFO in One Structure
Firmware constantly needs small queues for UART bytes. Putting the storage array and the bookkeeping fields in one structure keeps everything about one queue together, so you can create as many queues as you need without global variables.
#include <stdio.h>
#include <stdint.h>
#define FIFO_DEPTH 4
struct fifo {
uint8_t buf[FIFO_DEPTH];
uint8_t head;
uint8_t tail;
uint8_t count;
};
static int fifo_put(struct fifo *f, uint8_t v)
{
if (f->count == FIFO_DEPTH)
return -1;
f->buf[f->head] = v;
f->head = (uint8_t)((f->head + 1) % FIFO_DEPTH);
f->count++;
return 0;
}
static int fifo_get(struct fifo *f, uint8_t *v)
{
if (f->count == 0)
return -1;
*v = f->buf[f->tail];
f->tail = (uint8_t)((f->tail + 1) % FIFO_DEPTH);
f->count--;
return 0;
}
int main(void)
{
struct fifo rx = { {0}, 0, 0, 0 };
uint8_t v;
int i;
for (i = 10; i < 16; i++)
printf("put %d -> %s\n", i, fifo_put(&rx, (uint8_t)i) == 0 ? "ok" : "full");
while (fifo_get(&rx, &v) == 0)
printf("got %u\n", v);
printf("sizeof(struct fifo) = %zu\n", sizeof rx);
return 0;
}
gcc -std=c11 -Wall -Wextra -o e2 e2.c
./e2
Expected output:
put 10 -> ok
put 11 -> ok
put 12 -> ok
put 13 -> ok
put 14 -> full
put 15 -> full
got 10
got 11
got 12
got 13
sizeof(struct fifo) = 7
The queue holds four bytes, so the fifth and sixth put calls report full and the data is not lost or overwritten. The head index wraps with the modulo operator. The structure is 7 bytes: 4 for the buffer and 1 each for head, tail and count. Every member is one byte wide, so no padding appears.
fifo_put while the main loop calls fifo_get on the same queue, the count field can be updated by both sides at once. For real firmware use a single-producer single-consumer design without a shared count, or protect the operations with a critical section.Pitfalls Specific to Array Members
| Pitfall | Why it happens | Fix |
|---|---|---|
Overflowing name with strcpy | No bounds check; 16 bytes only | Use snprintf(r.name, sizeof r.name, "%s", src) |
Writing r.marks = {1,2,3,4}; after declaration | Braces work only in initialisers | Assign element by element, or copy from another structure |
| Using index 4 on a 4-element array | Valid indexes are 0 to 3 | Loop with j < SUBJECTS |
| Assuming the array is a pointer | It is storage inside the structure | Use sizeof r.marks to get 16, not the pointer size |
| Large array member passed by value | Whole array copied each call | Pass a pointer |
Best Practices
- Define the array length with a named constant so the structure and its loops always agree.
- Prefer
uint8_t,uint16_tand friends for buffers in firmware; the type then states the width. - Keep index fields small and validate before use.
- Use
static constfor read-only tables so they stay in flash.
Quiz: Structures in C
Try each question first, then open the answer. All code assumes a typical 32-bit or 64-bit desktop or Cortex-M compiler where int is 4 bytes.
Two variables of the same structure type, a and b. Which statement copies all members of a into b?
- A.
b == a; - B.
b = a; - C.
b + a; - D. Not possible
Show answer
B. Assignment between variables of the same structure type copies every member.
- A.
Which operation is NOT allowed directly on structure variables?
- A. Assignment
- B.
sizeof - C.
== - D. Taking the address with
&
Show answer
C. C has no equality operator for structures.
Members of a structure are stored in which order?
- A. Alphabetical
- B. Largest first
- C. Declaration order
- D. Random
Show answer
C. Declaration order at increasing addresses; padding may sit between them.
On a typical platform, what is sizeof of
struct { char a; int b; char c; }?- A. 6
- B. 8
- C. 12
- D. 9
Show answer
C. 12: a at 0, three padding bytes, b at 4, c at 8, three trailing padding bytes.
Reordering that structure as
int b; char a; char c;gives which size?- A. 6
- B. 8
- C. 12
- D. 4
Show answer
B. 8: 4 + 1 + 1 plus 2 trailing padding bytes.
What does
offsetof(struct pkt_hdr, seq)return?- A. The address of seq
- B. The byte distance from the start of the structure to seq
- C. The size of seq
- D. The value of seq
Show answer
B. It is a size_t byte offset, printed with %zu.
A structure contains
int marks[4]. Aftercopy = orig; copy.marks[0] = 0;what happens to orig.marks[0]?- A. It becomes 0
- B. It is unchanged
- C. Undefined
- D. Compile error
Show answer
B. The embedded array was copied by value, so orig is untouched.
How do you compute the number of elements of an array arr of structures?
- A.
sizeof(arr) - B.
sizeof(arr[0]) - C.
sizeof(arr) / sizeof(arr[0]) - D.
strlen(arr)
Show answer
C. Total bytes divided by bytes per element.
- A.
What does the packed attribute do?
- A. Adds padding
- B. Removes padding between members
- C. Encrypts the structure
- D. Moves it to flash
Show answer
B. It removes padding, at the cost of possible misaligned access.
Given
struct result batch[3]where batch[2].name is “Meena”, what isbatch[2].name[0]?- A. ‘e’
- B. ‘M’
- C. “Meena”
- D. 5
Show answer
B. Index 0 is the first character, M.
A function receives a structure by value and changes a member. What happens to the caller’s variable?
- A. Changed
- B. Unchanged
- C. Compile error
- D. Crash
Show answer
B. The function works on its own copy.
Which is the correct way to read a member through a pointer p to a structure?
- A.
p.value - B.
p->value - C.
*p.value - D.
&p.value
Show answer
B.
p->valueequals(*p).value.- A.
Predict the Output
struct pair { char c; int n; };
struct pair p = { 'x', 5 };
struct pair q = p;
q.n++;
printf("%d %d", p.n, q.n);
Show answer
It prints 5 6. q is an independent copy of p, so incrementing q.n does not affect p.n.
struct chan { const char *name; int raw; };
struct chan t[] = { {"A", 1}, {"B", 2}, {"C", 3} };
printf("%zu %c", sizeof t / sizeof t[0], t[2].name[0]);
Show answer
It prints 3 C: three elements, and the first character of the third name.
Programming Challenges
- Extend the student program to find the topper (highest total) and print the name.
- Add a
fifo_peekfunction that returns the next byte without removing it, and afifo_clearfunction. - Write a structure with members
char a; double d; short s; char b;, predict its size, verify withsizeofandoffsetof, then reorder to shrink it. - Write a function that compares two
struct resultvariables member by member and returns 1 if equal.
Interview Questions on Structures in C
What is structure padding and why does the compiler add it?
Padding is filler bytes inserted so members start at addresses suited to their type. Aligned access is faster and on some cores required, so the compiler pads between members and at the end.
How can you reduce the size of a structure without changing its data?
Order members from largest to smallest alignment. Packing is possible but can cost speed or cause faults.
Can two structures be compared with ==? How would you compare them?
No. Compare member by member. Avoid memcmp because padding bytes may differ.
What does assigning one structure to another do when it has a pointer member?
It copies the pointer value only, a shallow copy. Both structures then point at the same data.
What is the difference between passing a structure by value and by pointer?
By value copies the whole structure, which is safe but costly for large ones. By pointer passes an address; use const when the function must not modify it.
How do you find the offset of a member?
Use offsetof from stddef.h.
Why is sizeof used instead of adding member sizes?
Because padding makes the total larger than the sum, and the value can differ between platforms.
Is the size of a structure the same on a PC and on a Cortex-M?
Not guaranteed. Pointer size, long size and alignment rules can differ. Verify with static assertions.
How does the compiler lay out an array of structures?
Elements are contiguous, each with the same size, with any padding inside each element.
When is it unsafe to use a packed structure?
When you take the address of a member and pass it where an aligned pointer is expected, or on cores that fault on unaligned access.
How can an array be made copyable by assignment?
Wrap it in a structure. Assigning the structure copies the array.
How would you share a status structure between an interrupt handler and the main loop safely?
Copy it inside a short critical section, or use a lock-free single-writer design, since a structure copy is not atomic.
Key Takeaways
- An array member is stored in place inside the structure.
- Use
r.marks[j]orp->marks[j]to reach elements. - Wrapping an array in a structure makes it assignable and passable by value.
- Use
snprintfwithsizeoffor char array members. - Interrupt-shared structures need protection.
Frequently Asked Questions
Can a structure contain an array in C?
Yes. The array is stored inside the structure’s own memory, in place, and is copied when the whole structure is copied.
How do I access an element of an array that is inside a structure?
Use the dot operator then the subscript, for example r.marks[2], or through a pointer, p->marks[2].
Does assigning a structure copy its array member?
Yes. Every element of the array member is copied by value.
Can I initialise an array member with braces?
Yes, at declaration, for example { “Asha”, 1, { 80, 75, 90, 85 } }. After declaration you must assign elements individually.
How do I safely store a string in a char array member?
Use snprintf or strncpy with sizeof of the member so the text cannot overflow the array.
Is a structure with an array member a good fit for a ring buffer?
Yes. Keeping the buffer and its indexes in one structure lets you create several independent queues. Add protection if interrupts touch it.
Keep Learning C for Embedded Systems
This lecture is part of our free embedded C programming course. Practice every program on your own machine, then move on to the next lecture.

1 Comment