The Wayback Machine - https://web.archive.org/web/20241019155358/https://www.geeksforgeeks.org/flexible-array-members-structure-c/
Open In App

Flexible Array Members in a structure in C

Last Updated : 20 Aug, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Flexible Array Member(FAM) is a feature introduced in the C99 standard of the C programming language.

  • For the structures in C programming language from C99 standard onwards, we can declare an array without a dimension and whose size is flexible in nature.
  • Such an array inside the structure should preferably be declared as the last member of the structure and its size is variable(can be changed at runtime).
  • The structure must contain at least one more named member in addition to the flexible array member.

What must be the size of the structure below?

C
struct student {
    int stud_id;
    int name_len;
    int struct_size;
    char stud_name[];
};
The size of structure is = 4 + 4 + 4 + 0 = 12

In the above code snippet, the size i.e. length of array “stud_name” isn’t fixed and is a FAM. The memory allocation using flexible array members(as per C99 standards) for the above example can be done as:

struct student *s = malloc( sizeof(*s) + sizeof(char [strlen(stud_name)])  );

Note: While using flexible array members in structures some convention regarding the actual size of the member is defined. The convention is that the flexible array member does not contribute to the size of the structure itself. Instead, the size of the structure is determined by the other data members plus any memory allocated dynamically for the flexible array.

In the above example, the convention is that the member “stud_name” has a size of the number of characters stored.

For Example, Consider the following structure:

Input : id = 15, name = "Kartik" 
Output : Student_id : 15
Stud_Name : Kartik
Name_Length: 6
Allocated_Struct_size: 18

Memory allocation of the above structure: 

struct student *s = 
malloc( sizeof(*s) + sizeof(char [strlen("Kartik")]));

Its structure representation is equal to: 

C
struct student {
    int stud_id;
    int name_len;
    int struct_size;
    char stud_name[6]; // character array of length 6
};

Example

The below C program shows the implementation of flexible array members.

C
// C program for variable length members in
// structures in GCC
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

// A structure of type student
struct student {
    int stud_id;
    int name_len;

    // This is used to store size of flexible
    // character array stud_name[]
    int struct_size;

    // Flexible Array Member (FAM)
    // variable length array must be last
    // member of structure
    char stud_name[];
};

// Memory allocation and initialization of structure
struct student* createStudent(int id, char a[]) {
    // Allocate memory for the struct and the flexible array member
    struct student *s = malloc(sizeof(*s) + sizeof(char) * (strlen(a) + 1)); // +1 for null terminator

    if (s == NULL) {
        perror("Failed to allocate memory");
        exit(EXIT_FAILURE);
    }

    s->stud_id = id;
    s->name_len = strlen(a);
    strcpy(s->stud_name, a);  // Copy the name into the flexible array member

    // Assign size according to the size of stud_name
    s->struct_size = sizeof(*s) + sizeof(char) * (strlen(s->stud_name) + 1);

    return s;
}

// Print student details
void printStudent(struct student* s) {
    printf("Student_id : %d\n"
           "Stud_Name : %s\n"
           "Name_Length: %d\n"
           "Allocated_Struct_size: %d\n\n",
           s->stud_id, s->stud_name, s->name_len,
           s->struct_size);

    // Value of Allocated_Struct_size is in bytes here
}

// Driver Code
int main() {
    struct student* s1 = createStudent(523, "Cherry");
    struct student* s2 = createStudent(535, "Sanjayulsha");

    printStudent(s1);
    printStudent(s2);

    // Size in struct student
    printf("Size of Struct student: %lu\n", sizeof(struct student));

    // Size in struct pointer
    printf("Size of Struct pointer: %lu\n", sizeof(s1));

    // Free allocated memory
    free(s1);
    free(s2);

    return 0;
}

Output
Student_id : 523
Stud_Name : Cherry
Name_Length: 6
Allocated_Struct_size: 19

Student_id : 535
Stud_Name : Sanjayulsha
Name_Length: 11
Allocated_Struct_size: 24

Size of Struct student: 12
Size of Struct pointer: 8


Output

Student_id : 523
Stud_Name : SanjayKanna
Name_Length: 11
Allocated_Struct_size: 23

Student_id : 535
Stud_Name : Cherry
Name_Length: 6
Allocated_Struct_size: 18

Size of Struct student: 12
Size of Struct pointer: 8

Important Points

  1. Adjacent memory locations are used to store structure members in memory.
  2. In previous standards of the C programming language, we were able to declare a zero-size array member in place of a flexible array member. The GCC compiler with C89 standard considers it as zero size array.



Previous Article
Next Article

Similar Reads

Static Data Structure vs Dynamic Data Structure
Data structure is a way of storing and organizing data efficiently such that the required operations on them can be performed be efficient with respect to time as well as memory. Simply, Data Structure are used to reduce complexity (mostly the time complexity) of the code. Data structures can be two types : 1. Static Data Structure 2. Dynamic Data
4 min read
Array of Structures vs Array within a Structure in C
Both Array of Structures and Array within a Structure in C programming is a combination of arrays and structures but both are used to serve different purposes. Array within a StructureA structure is a data type in C that allows a group of related variables to be treated as a single unit instead of separate entities. A structure may contain elements
5 min read
Comparison of an Array and Hash table in terms of Storage structure and Access time complexity
Arrays and Hash Tables are two of the most widely used data structures in computer science, both serving as efficient solutions for storing and accessing data in Java. They have different storage structures and time complexities, making them suitable for different use cases. In this article, we will explore the differences between arrays and hash t
3 min read
Remove duplicates from unsorted array using Map data structure
Given an unsorted array of integers, print the array after removing the duplicate elements from it. We need to print distinct array elements according to their first occurrence. Examples: Input : arr[] = { 1, 2, 5, 1, 7, 2, 4, 2} Output : 1 2 5 7 4 Explanation : {1, 2} appear more than one time. Approach : Take a hash map, which will store all the
4 min read
Remove duplicates from unsorted array using Set data structure
Given an unsorted array of integers, print the array after removing the duplicate elements from it. We need to print distinct array elements according to their first occurrence. Examples: Input: arr[] = { 1, 2, 5, 1, 7, 2, 4, 2} Output: 1 2 5 7 4 Explanation: {1, 2} appear more than one time. Input: arr[] = { 3, 3, 4, 1, 1} Output: 3 4 1 Approach:
3 min read
Differences between Array and Dictionary Data Structure
Arrays:The array is a collection of the same type of elements at contiguous memory locations under the same name. It is easier to access the element in the case of an array. The size is the key issue in the case of an array which must be known in advance so as to store the elements in it. Insertion and deletion operations are costly in the case of
5 min read
Is array a Data Type or Data Structure?
What is Data Type? In computer programming, a data type is a classification of data that determines the type of values that can be stored, manipulated, and processed. It tells the computer what kind of data a particular variable or constant can hold, and what operations can be performed on that data. Common data types include integers, floating-poi
8 min read
Array Data Structure
Complete Guide to ArraysLearn more about Array in DSA Self Paced CoursePractice Problems on ArraysTop Quizzes on Arrays What is Array?An array is a collection of items stored at contiguous memory locations. The idea is to store multiple items of the same type together. This makes it easier to calculate the position of each element by simply adding
3 min read
Getting Started with Array Data Structure
Array is a collection of items of the same variable type that are stored at contiguous memory locations. It is one of the most popular and simple data structures used in programming. In this article, we have decided to provide a complete guide for Arrays, which will help you to tackle any problem based on Arrays. Table of Content What is an Array?B
15+ min read
Array Data Structure Guide
In this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) at contiguous locations or their references (in case of Python, JS, Java Non-Primitive( at contiguous locations. It offers mainl
4 min read
Modify array to another given array by replacing array elements with the sum of the array
Given an array input[] consisting only of 1s initially and an array target[] of size N, the task is to check if the array input[] can be converted to target[] by replacing input[i] with the sum of array elements in each step. If found to be true, then print "YES". Otherwise, print "NO". Examples: Input: input[] = { 1, 1, 1 }, target[] = { 9, 3, 5 }
13 min read
Modify array to another given array by replacing array elements with the sum of the array | Set-2
Given an Array input[] consisting only of 1s initially and an array target[] of size N, the task is to check if the array input[] can be converted to target[] by replacing input[i] with the sum of array elements in each step. Examples: Input: input[] = { 1, 1, 1 }, target[] = { 9, 3, 5 } Output: YES Explanation: Replacing input[1] with (input[0] +
10 min read
Applications of Queue Data Structure
Introduction : A queue is a linear data structure that follows the "first-in, first-out" (FIFO) principle. It is a collection of elements that supports two primary operations - enqueue and dequeue. In the enqueue operation, an element is added to the back of the queue, while in the dequeue operation, an element is removed from the front of the queu
5 min read
Data Structure for a single resource reservations
Design a data structure to do reservations of future jobs on a single machine under following constraints. Every job requires exactly k time units of the machine. The machine can do only one job at a time. Time is part of the system. Future Jobs keep coming at different times. Reservation of a future job is done only if there is no existing reserva
7 min read
A data structure for n elements and O(1) operations
Propose a data structure for the following: The data structure would hold elements from 0 to n-1. There is no order on the elements (no ascending/descending order requirement) The complexity of the operations should be as follows: Insertion of an element – O(1) Deletion of an element – O(1) Finding an element – O(1) We strongly recommend to minimiz
4 min read
Tango Tree Data Structure
INTRODUCTION:' Tango Tree is a data structure for efficient dynamic connectivity and range minimum/maximum query on a set of elements. It is a type of balanced binary search tree that uses finger trees as the underlying data structure to achieve fast and efficient operations. The Tango Tree is designed to support both fast insertions and deletions
4 min read
Applications of Graph Data Structure
A graph is a non-linear data structure, which consists of vertices(or nodes) connected by edges(or arcs) where edges may be directed or undirected. In Computer science graphs are used to represent the flow of computation.Google maps uses graphs for building transportation systems, where intersection of two(or more) roads are considered to be a vert
3 min read
Which data structure is used by Map?
What is a Map? Before learning the data structure used by a map, let us have an overlook of map. Map is the part of the STL library that stores key value pairs in it and no two values have the same keys but the different keys can store similar values. The map stores keys in sorted order. These are some functions which map uses with their Time Compl
2 min read
Sudo Placement 2 | Course Structure
Course Home Page Week Aptitude Verbal Ability Logical Reasoning Basic Programming Week 1 Ratio, Proportion, and Progressions Basic Grammar Number Series, Symbol Series Operators, DataTypes, Loops & Control Structure Week 2 Percentages, Profit and Loss Spotting Errors Verbal Classification, Essential Part Loops & Control Structure, Functions Week 3
1 min read
Check if two trees have same structure
Given two binary trees. The task is to write a program to check if the two trees are identical in structure. In the above figure both of the trees, Tree1 and Tree2 are identical in structure. That is, they have the same structure. Note: This problem is different from Check if two trees are identical as here we need to compare only the structures of
8 min read
Applications of linked list data structure
A linked list is a linear data structure, in which the elements are not stored at contiguous memory locations. The elements in a linked list are linked using pointers as shown in the below image: Applications of linked list in computer science:Implementation of stacks and queuesImplementation of graphs: Adjacency list representation of graphs is th
5 min read
Top 50 Problems on Heap Data Structure asked in SDE Interviews
A Heap is a special Tree-based Data Structure in which the tree is a complete binary tree. Generally, heaps are of two types: Max-Heap and Min-Heap. To know more about this Data Structure in-depth refer to the Tutorial on Heap Data-Structure. Given below are the most frequently asked interview questions on Heaps:  Easy Interview Questions on Heap D
2 min read
Map Policy Based Data Structure in g++
There are some data structures that are supported by g++ compiler and are not a part of the C++ standard library. One of these is: Policy-Based Data Structure, which is used for high-performance, flexibility, semantic safety, and conformance to the corresponding containers in std. This can also be used as a map, to store key and a value (pair) in a
3 min read
Trie Data Structure using smart pointer and OOP in C++
We will implement trie using smart pointers in C++ and OOP. Here, We have already discussed the implementation of trie data using recursionIn our implementation node of a trie look like : C/C++ Code class TrieNode{ public: // Use of shared_ptr for storing Children // Pointers of TrieNode shared_ptr children[ALPHABET_SIZE]; // Tracks whether If this
6 min read
Count-Min Sketch Data Structure with Implementation
The Count-Min Sketch is a probabilistic data structure and is defined as a simple technique to summarize large amounts of frequency data. Count-min sketch algorithm talks about keeping track of the count of things. i.e, How many times an element is present in the set. What is Count-Min Sketch?Count-min sketch approach was proposed by Graham Cormode
7 min read
Introduction to the Probabilistic Data Structure
Introduction: Probabilistic Data Structures are data structures that provide approximate answers to queries about a large dataset, rather than exact answers. These data structures are designed to handle large amounts of data in real-time, by making trade-offs between accuracy and time and space efficiency. Some common examples of Probabilistic Data
5 min read
Create a Circular List Structure For Given Value K Using Recursion
Given a number K, the task is to create the circular linked list structure with four pointers that are next, previous, up, and down Using Recursion. Note: You are not allowed to use any array of pointers or 2D matrixSee this example for K = 3 Examples: Input: k = 3 Output: 1 2 3 4 5 6 7 8 9 Explanation: The structure will look like below Approach:
15+ min read
Greedy Algorithms (General Structure and Applications)
The general structure of a greedy algorithm can be summarized in the following steps:Identify the problem as an optimization problem where we need to find the best solution among a set of possible solutions.Determine the set of feasible solutions for the problem.Identify the optimal substructure of the problem, meaning that the optimal solution to
9 min read
Sort a 2D vector diagonally using Map Data Structure
Given a 2D vector mat[][] of integers. The task is to sort the elements of the vectors diagonally from top-left to bottom-right in increasing order.Examples: Input: mat[][] = {{9, 4, 2}, {7, 4, 6}, {2, 3, 3}} Output: 3 4 2 3 4 6 2 7 9 Explanation: There are 5 diagonals in this matrix: 1. {2} - No need to sort 2. {7, 3} - Sort - {3, 7} 3. {9, 4, 3}
8 min read
Design a structure which supports insertion and first non-repeating element in O(1) time
Design a Data structure which supports insertion and first non-repeating element in O(1) time. Operations that are supported by the data structure: Insertion: Insert a element into the data structure.First non-repeating Element: First non-repeating element into the array. Note: If there is no non-repeating element in the array then print -1. Consid
12 min read
Practice Tags :
three90RightbarBannerImg