Next: Unions , Previous: Overlaying Structures , Up: Structures   [ Contents ][ Index ]

15.13 Structure Assignment

Assignment operating on a structure type copies the structure. The left and right operands must have the same type. Here is an example:

Notionally, assignment on a structure type works by copying each of the fields. Thus, if any of the fields has the const qualifier, that structure type does not allow assignment:

See Assignment Expressions .

When a structure type has a field which is an array, as here,

structure assigment such as r1 = r2 copies array fields’ contents just as it copies all the other fields.

This is the only way in C that you can operate on the whole contents of a array with one operation: when the array is contained in a struct . You can’t copy the contents of the data field as an array, because

would convert the array objects (as always) to pointers to the zeroth elements of the arrays (of type struct record * ), and the assignment would be invalid because the left operand is not an lvalue.

C Programming/Pointers and arrays

A pointer is a value that designates the address (i.e., the location in memory), of some value. Pointers are variables that hold a memory location.

There are four fundamental things you need to know about pointers:

  • How to declare them (with the address operator ' & ': int *pointer = &variable; )
  • How to assign to them ( pointer = NULL; )
  • How to reference the value to which the pointer points (known as dereferencing , by using the dereferencing operator ' * ': value = *pointer; )
  • How they relate to arrays (the vast majority of arrays in C are simple lists, also called "1 dimensional arrays", but we will briefly cover multi-dimensional arrays with some pointers in a later chapter ).

Pointers can reference any data type, even functions. We'll also discuss the relationship of pointers with text strings and the more advanced concept of function pointers.

  • 1 Declaring pointers
  • 2 Assigning values to pointers
  • 3 Pointer dereferencing
  • 4 Pointers and Arrays
  • 5 Pointers in Function Arguments
  • 6 Pointers and Text Strings
  • 7.1 Practical use of function pointers in C
  • 8 Examples of pointer constructs
  • 10 External Links

Declaring pointers [ edit | edit source ]

Consider the following snippet of code which declares two pointers:

Lines 1-4 define a structure . Line 8 declares a variable that points to an int , and line 9 declares a variable that points to something with structure MyStruct. So to declare a variable as something that points to some type, rather than contains some type, the asterisk ( * ) is placed before the variable name.

In the following, line 1 declares var1 as a pointer to a long and var2 as a long and not a pointer to a long. In line 2, p3 is declared as a pointer to a pointer to an int.

Pointer types are often used as parameters to function calls. The following shows how to declare a function which uses a pointer as an argument. Since C passes function arguments by value, in order to allow a function to modify a value from the calling routine, a pointer to the value must be passed. Pointers to structures are also used as function arguments even when nothing in the struct will be modified in the function. This is done to avoid copying the complete contents of the structure onto the stack. More about pointers as function arguments later.

Assigning values to pointers [ edit | edit source ]

So far we've discussed how to declare pointers. The process of assigning values to pointers is next. To assign the address of a variable to a pointer, the & or 'address of' operator is used.

Here, pPointer will now reference myInt and pKeyboard will reference dvorak.

Pointers can also be assigned to reference dynamically allocated memory. The malloc() and calloc() functions are often used to do this.

The malloc function returns a pointer to dynamically allocated memory (or NULL if unsuccessful). The size of this memory will be appropriately sized to contain the MyStruct structure.

The following is an example showing one pointer being assigned to another and of a pointer being assigned a return value from a function.

When returning a pointer from a function, do not return a pointer that points to a value that is local to the function or that is a pointer to a function argument. Pointers to local variables become invalid when the function exits. In the above function, the value returned points to a static variable. Returning a pointer to dynamically allocated memory is also valid.

Pointer dereferencing [ edit | edit source ]

To access a value to which a pointer points, the * operator is used. Another operator, the -> operator is used in conjunction with pointers to structures. Here's a short example.

The expression bb->m_aNumber is entirely equivalent to (*bb).m_aNumber . They both access the m_aNumber element of the structure pointed to by bb . There is one more way of dereferencing a pointer, which will be discussed in the following section.

When dereferencing a pointer that points to an invalid memory location, an error often occurs which results in the program terminating. The error is often reported as a segmentation error. A common cause of this is failure to initialize a pointer before trying to dereference it.

C is known for giving you just enough rope to hang yourself, and pointer dereferencing is a prime example. You are quite free to write code that accesses memory outside that which you have explicitly requested from the system. And many times, that memory may appear as available to your program due to the vagaries of system memory allocation. However, even if 99 executions allow your program to run without fault, that 100th execution may be the time when your "memory pilfering" is caught by the system and the program fails. Be careful to ensure that your pointer offsets are within the bounds of allocated memory!

The declaration void *somePointer; is used to declare a pointer of some nonspecified type. You can assign a value to a void pointer, but you must cast the variable to point to some specified type before you can dereference it. Pointer arithmetic is also not valid with void * pointers.

Pointers and Arrays [ edit | edit source ]

Up to now, we've carefully been avoiding discussing arrays in the context of pointers. The interaction of pointers and arrays can be confusing but here are two fundamental statements about it:

  • A variable declared as an array of some type acts as a pointer to that type. When used by itself, it points to the first element of the array.
  • A pointer can be indexed like an array name.

The first case often is seen to occur when an array is passed as an argument to a function. The function declares the parameter as a pointer, but the actual argument may be the name of an array. The second case often occurs when accessing dynamically allocated memory.

Let's look at examples of each. In the following code, the call to calloc() effectively allocates an array of struct MyStruct items.

Pointers and array names can pretty much be used interchangeably; however, there are exceptions. You cannot assign a new pointer value to an array name. The array name will always point to the first element of the array. In the function returnSameIfAnyEquals , you could however assign a new value to workingArray, as it is just a pointer to the first element of workingArray. It is also valid for a function to return a pointer to one of the array elements from an array passed as an argument to a function. A function should never return a pointer to a local variable, even though the compiler will probably not complain.

When declaring parameters to functions, declaring an array variable without a size is equivalent to declaring a pointer. Often this is done to emphasize the fact that the pointer variable will be used in a manner equivalent to an array.

Now we're ready to discuss pointer arithmetic. You can add and subtract integer values to/from pointers. If myArray is declared to be some type of array, the expression *(myArray+j) , where j is an integer, is equivalent to myArray[j] . For instance, in the above example where we had the expression secondArray[i].otherNumber , we could have written that as (*(secondArray+i)).otherNumber or more simply (secondArray+i)->otherNumber .

Note that for addition and subtraction of integers and pointers, the value of the pointer is not adjusted by the integer amount, but is adjusted by the amount multiplied by the size of the type to which the pointer refers in bytes. (For example, pointer + x can be thought of as pointer + (x * sizeof(*type)) .)

One pointer may also be subtracted from another, provided they point to elements of the same array (or the position just beyond the end of the array). If you have a pointer that points to an element of an array, the index of the element is the result when the array name is subtracted from the pointer. Here's an example.

You may be wondering how pointers and multidimensional arrays interact. Let's look at this a bit in detail. Suppose A is declared as a two dimensional array of floats ( float A[D1][D2]; ) and that pf is declared a pointer to a float. If pf is initialized to point to A[0][0], then *(pf+1) is equivalent to A[0][1] and *(pf+D2) is equivalent to A[1][0]. The elements of the array are stored in row-major order.

Let's look at a slightly different problem. We want to have a two dimensional array, but we don't need to have all the rows the same length. What we do is declare an array of pointers. The second line below declares A as an array of pointers. Each pointer points to a float. Here's some applicable code:

We also note here something curious about array indexing. Suppose myArray is an array and i is an integer value. The expression myArray[i] is equivalent to i[myArray] . The first is equivalent to *(myArray+i) , and the second is equivalent to *(i+myArray) . These turn out to be the same, since the addition is commutative.

Pointers can be used with pre-increment or post-decrement, which is sometimes done within a loop, as in the following example. The increment and decrement applies to the pointer, not to the object to which the pointer refers. In other words, *pArray++ is equivalent to *(pArray++) .

Pointers in Function Arguments [ edit | edit source ]

Often we need to invoke a function with an argument that is itself a pointer. In many instances, the variable is itself a parameter for the current function and may be a pointer to some type of structure. The ampersand ( & ) character is not needed in this circumstance to obtain a pointer value, as the variable is itself a pointer. In the example below, the variable pStruct , a pointer, is a parameter to function FunctTwo , and is passed as an argument to FunctOne .

The second parameter to FunctOne is an int. Since in function FunctTwo , mValue is a pointer to an int, the pointer must first be dereferenced using the * operator, hence the second argument in the call is *mValue . The third parameter to function FunctOne is a pointer to a long. Since pAA is itself a pointer to a long, no ampersand is needed when it is used as the third argument to the function.

Pointers and Text Strings [ edit | edit source ]

Historically, text strings in C have been implemented as arrays of characters, with the last byte in the string being a zero, or the null character '\0'. Most C implementations come with a standard library of functions for manipulating strings. Many of the more commonly used functions expect the strings to be null terminated strings of characters. To use these functions requires the inclusion of the standard C header file "string.h".

A statically declared, initialized string would look similar to the following:

The variable myFormat can be viewed as an array of 21 characters. There is an implied null character ('\0') tacked on to the end of the string after the 'd' as the 21st item in the array. You can also initialize the individual characters of the array as follows:

An initialized array of strings would typically be done as follows:

The initialization of an especially long string can be split across lines of source code as follows.

The library functions that are used with strings are discussed in a later chapter.

Pointers to Functions [ edit | edit source ]

C also allows you to create pointers to functions. Pointers to functions syntax can get rather messy. As an example of this, consider the following functions:

Declaring a typedef to a function pointer generally clarifies the code. Here's an example that uses a function pointer, and a void * pointer to implement what's known as a callback. The DoSomethingNice function invokes a caller supplied function TalkJive with caller data. Note that DoSomethingNice really doesn't know anything about what dataPointer refers to.

Some versions of C may not require an ampersand preceding the TalkJive argument in the DoSomethingNice call. Some implementations may require specifically casting the argument to the MyFunctionType type, even though the function signature exacly matches that of the typedef.

Function pointers can be useful for implementing a form of polymorphism in C. First one declares a structure having as elements function pointers for the various operations to that can be specified polymorphically. A second base object structure containing a pointer to the previous structure is also declared. A class is defined by extending the second structure with the data specific for the class, and static variable of the type of the first structure, containing the addresses of the functions that are associated with the class. This type of polymorphism is used in the standard library when file I/O functions are called.

A similar mechanism can also be used for implementing a state machine in C. A structure is defined which contains function pointers for handling events that may occur within state, and for functions to be invoked upon entry to and exit from the state. An instance of this structure corresponds to a state. Each state is initialized with pointers to functions appropriate for the state. The current state of the state machine is in effect a pointer to one of these states. Changing the value of the current state pointer effectively changes the current state. When some event occurs, the appropriate function is called through a function pointer in the current state.

Practical use of function pointers in C [ edit | edit source ]

Function pointers are mainly used to reduce the complexity of switch statement. Example with switch statement:

Without using a switch statement:

Function pointers may be used to create a struct member function:

Use to implement this pointer (following code must be placed in library).

Examples of pointer constructs [ edit | edit source ]

Below are some example constructs which may aid in creating your pointer.

sizeof [ edit | edit source ]

The sizeof operator is often used to refer to the size of a static array declared earlier in the same function.

To find the end of an array (example from wikipedia:Buffer overflow ):

To iterate over every element of an array, use

Note that the sizeof operator only works on things defined earlier in the same function. The compiler replaces it with some fixed constant number. In this case, the buffer was declared as an array of 10 char's earlier in the same function, and the compiler replaces sizeof(buffer) with the number 10 at compile time (equivalent to us hard-coding 10 into the code in place of sizeof(buffer) ). The information about the length of buffer is not actually stored anywhere in memory (unless we keep track of it separately) and cannot be programmatically obtained at run time from the array/pointer itself.

Often a function needs to know the size of an array it was given -- an array defined in some other function. For example,

Unfortunately, (in C and C++) the length of the array cannot be obtained from an array passed in at run time, because (as mentioned above) the size of an array is not stored anywhere. The compiler always replaces sizeof with a constant. This sum() routine needs to handle more than just one constant length of an array.

There are some common ways to work around this fact:

  • Write the function to require, for each array parameter, a "length" parameter (which has type "size_t"). (Typically we use sizeof at the point where this function is called).
  • Use of a convention, such as a null-terminated string to mark the end of the array.
  • Instead of passing raw arrays, pass a structure that includes the length of the array (such as ".length") as well as the array (or a pointer to the first element); similar to the string or vector classes in C++.

It's worth mentioning that sizeof operator has two variations: sizeof ( type ) (for instance: sizeof (int) or sizeof (struct some_structure) ) and sizeof expression (for instance: sizeof some_variable.some_field or sizeof 1 ).

External Links [ edit | edit source ]

  • "Common Pointer Pitfalls" by Dave Marshall

c assign array in struct

  • Book:C Programming

Navigation menu

C Functions

C structures, c structures (structs).

Structures (also called structs) are a way to group several related variables into one place. Each variable in the structure is known as a member of the structure.

Unlike an array , a structure can contain many different data types (int, float, char, etc.).

Create a Structure

You can create a structure by using the struct keyword and declare each of its members inside curly braces:

To access the structure, you must create a variable of it.

Use the struct keyword inside the main() method, followed by the name of the structure and then the name of the structure variable:

Create a struct variable with the name "s1":

Access Structure Members

To access members of a structure, use the dot syntax ( . ):

Now you can easily create multiple structure variables with different values, using just one structure:

What About Strings in Structures?

Remember that strings in C are actually an array of characters, and unfortunately, you can't assign a value to an array like this:

An error will occur:

However, there is a solution for this! You can use the strcpy() function and assign the value to s1.myString , like this:

Simpler Syntax

You can also assign values to members of a structure variable at declaration time, in a single line.

Just insert the values in a comma-separated list inside curly braces {} . Note that you don't have to use the strcpy() function for string values with this technique:

Note: The order of the inserted values must match the order of the variable types declared in the structure (13 for int, 'B' for char, etc).

Copy Structures

You can also assign one structure to another.

In the following example, the values of s1 are copied to s2:

Modify Values

If you want to change/modify a value, you can use the dot syntax ( . ).

And to modify a string value, the strcpy() function is useful again:

Modifying values are especially useful when you copy structure values:

Ok, so, how are structures useful?

Imagine you have to write a program to store different information about Cars, such as brand, model, and year. What's great about structures is that you can create a single "Car template" and use it for every cars you make. See below for a real life example.

Real-Life Example

Use a structure to store different information about Cars:

C Exercises

Test yourself with exercises.

Fill in the missing part to create a Car structure:

Start the Exercise

Get Certified

COLOR PICKER

colorpicker

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

[email protected]

Top Tutorials

Top references, top examples, get certified.

Codeforwin

How to declare, initialize and access array of structure

  • Declare array of structure
  • Initialize structure array
  • Access structure array
  • Example program

Write a C program declare, initialize and access array of structure. In this post, I will explain how to declare, initialize and access array of structure in C programming. We will learn different ways of initializing structure array and accessing its.

Required knowledge

Basic C programming , Loop , Array , Structures

Declare, initialize and access array of structures in C programming language

In previous post we discussed how to declare and use structures in C language. Hence, I would not go deep discussing about basics of structures declaration.

How to declare array of structure?

Structure array declaration follows the normal array declaration syntax . Since, array of structure is a normal structure object only. Which we can declare structure array in two ways.

  • Along with structure declaration
  • After structure declaration

Declare array of structure along with structure declaration

The following code declares a structure to store student details. Along with the structure declaration it declares an array of structure object to store 100 student details.

Declare array of structure after structure declaration

The following code declares a student structure as we did above. After structure declaration it declares an array of student structure, capable of storing 100 student marks.

How to initialize structure array?

Structure array initialization follows same syntax as you initialize single structure object. The only difference is here you can initialize more than one structure object at a time.

How to access array of structure?

To access any structure object, you need to combine array indexed and structure member accessing technique. You can use either dot . or arrow -> (for pointers) operator to access structure array.

The above code assigns data to first array object. You can also use loop to iterate for all array object.

Program to declare, initialize and access array of structure

Happy coding 😉

Intro to C for CS31 Students

Part 2: structs & pointers.

  • Pointers and Functions C style "pass by referece"
  • Dynamic Memory Allocation (malloc and free)
  • Pointers to Structs

Defining a struct type

Declaring variables of struct types, accessing field values, passing structs to functions, rules for using pointer variables.

  • Next, initialize the pointer variable (make it point to something). Pointer variables store addresses . Initialize a pointer to the address of a storage location of the type to which it points. One way to do this is to use the ampersand operator on regular variable to get its address value: int x; char ch; ptr = &x; // ptr get the address of x, pointer "points to" x ------------ ------ ptr | addr of x|--------->| ?? | x ------------ ------ cptr = &ch; // ptr get the address of ch, pointer "points to" ch cptr = &x; // ERROR! cptr can hold a char address only (it's NOT a pointer to an int) All pointer variable can be set to a special value NULL . NULL is not a valid address but it is useful for testing a pointer variable to see if it points to a valid memory address before we access what it points to: ptr = NULL; ------ ------ cptr = NULL; ptr | NULL |-----| cptr | NULL |----| ------ ------
  • Use *var_name to dereference the pointer to access the value in the location that it points to. Some examples: int *ptr1, *ptr2, x, y; x = 8; ptr1 = NULL; ptr2 = &x; ------------ ------ ptr2 | addr of x|--------->| 8 | x ------------ ------ *ptr2 = 10; // dereference ptr2: "what ptr2 points to gets 10" ------------ ----- ptr2 | addr of x|--------->| 10 | x ------------ ----- y = *ptr2 + 3; // dereference ptr2: "y gets what ptr2 points to plus 3" ----- ----- ptr1 = ptr2; // ptr1 gets address value stored in ptr2 ------------ ----- ptr2 | addr of x |--------->| 10 | x ------------ ----- /\ ------------ | ptr1 | addr of x |-------------- ------------ // TODO: finish tracing through this code and show what is printed *ptr1 = 100; ptr1 = &y; *ptr1 = 80; printf("x = %d y = %d\n", x, y); printf("x = %d y = %d\n", *ptr2, *ptr1);
  • and what does this mean with respect to the value of each argument after the call?
  • Implement a program with a swap function that swaps the values stored in its two arguments. Make some calls to it in main to test it out.

malloc and free

Pointers, the heap, and functions, linked lists in c.

C Programming Tutorial

  • Array of Structures in C

Last updated on July 27, 2020

Declaring an array of structure is same as declaring an array of fundamental types. Since an array is a collection of elements of the same type. In an array of structures, each element of an array is of the structure type.

Let's take an example:

Here is how we can declare an array of structure car .

c assign array in struct

Here arr_car is an array of 10 elements where each element is of type struct car . We can use arr_car to store 10 structure variables of type struct car . To access individual elements we will use subscript notation ( [] ) and to access the members of each element we will use dot ( . ) operator as usual.

and so on. Similarly,

Recall that the precedence of [] array subscript and dot( . ) operator is same and they evaluates from left to right. Therefore in the above expression first array subscript( [] ) is applied followed by dot ( . ) operator. The array subscript ( [] ) and dot( . ) operator is same and they evaluates from left to right. Therefore in the above expression first [] array subscript is applied followed by dot ( . ) operator.

Let's rewrite the program we used in the last chapter as an introduction to structures.

Expected Output:

How it works:

In lines 5-10, we have declared a structure called the student .

In line 14, we have declared an array of structures of type struct student whose size is controlled by symbolic constant MAX . If you want to increase/decrease the size of the array just change the value of the symbolic constant and our program will adapt to the new size.

In line 17-29, the first for loop is used to enter the details of the student.

In line 36-40, the second for loop prints all the details of the student in tabular form.

Initializing Array of Structures #

We can also initialize the array of structures using the same syntax as that for initializing arrays. Let's take an example:

Load Comments

  • Intro to C Programming
  • Installing Code Blocks
  • Creating and Running The First C Program
  • Basic Elements of a C Program
  • Keywords and Identifiers
  • Data Types in C
  • Constants in C
  • Variables in C
  • Input and Output in C
  • Formatted Input and Output in C
  • Arithmetic Operators in C
  • Operator Precedence and Associativity in C
  • Assignment Operator in C
  • Increment and Decrement Operators in C
  • Relational Operators in C
  • Logical Operators in C
  • Conditional Operator, Comma operator and sizeof() operator in C
  • Implicit Type Conversion in C
  • Explicit Type Conversion in C
  • if-else statements in C
  • The while loop in C
  • The do while loop in C
  • The for loop in C
  • The Infinite Loop in C
  • The break and continue statement in C
  • The Switch statement in C
  • Function basics in C
  • The return statement in C
  • Actual and Formal arguments in C
  • Local, Global and Static variables in C
  • Recursive Function in C
  • One dimensional Array in C
  • One Dimensional Array and Function in C
  • Two Dimensional Array in C
  • Pointer Basics in C
  • Pointer Arithmetic in C
  • Pointers and 1-D arrays
  • Pointers and 2-D arrays
  • Call by Value and Call by Reference in C
  • Returning more than one value from function in C
  • Returning a Pointer from a Function in C
  • Passing 1-D Array to a Function in C
  • Passing 2-D Array to a Function in C
  • Array of Pointers in C
  • Void Pointers in C
  • The malloc() Function in C
  • The calloc() Function in C
  • The realloc() Function in C
  • String Basics in C
  • The strlen() Function in C
  • The strcmp() Function in C
  • The strcpy() Function in C
  • The strcat() Function in C
  • Character Array and Character Pointer in C
  • Array of Strings in C
  • Array of Pointers to Strings in C
  • The sprintf() Function in C
  • The sscanf() Function in C
  • Structure Basics in C
  • Array as Member of Structure in C
  • Nested Structures in C
  • Pointer to a Structure in C
  • Pointers as Structure Member in C
  • Structures and Functions in C
  • Union Basics in C
  • typedef statement in C
  • Basics of File Handling in C
  • fputc() Function in C
  • fgetc() Function in C
  • fputs() Function in C
  • fgets() Function in C
  • fprintf() Function in C
  • fscanf() Function in C
  • fwrite() Function in C
  • fread() Function in C

Recent Posts

  • Machine Learning Experts You Should Be Following Online
  • 4 Ways to Prepare for the AP Computer Science A Exam
  • Finance Assignment Online Help for the Busy and Tired Students: Get Help from Experts
  • Top 9 Machine Learning Algorithms for Data Scientists
  • Data Science Learning Path or Steps to become a data scientist Final
  • Enable Edit Button in Shutter In Linux Mint 19 and Ubuntu 18.04
  • Python 3 time module
  • Pygments Tutorial
  • How to use Virtualenv?
  • Installing MySQL (Windows, Linux and Mac)
  • What is if __name__ == '__main__' in Python ?
  • Installing GoAccess (A Real-time web log analyzer)
  • Installing Isso

Learn C practically and Get Certified .

Popular Tutorials

Popular examples, reference materials, learn c interactively, c introduction.

  • Keywords & Identifier
  • Variables & Constants
  • C Data Types
  • C Input/Output
  • C Operators
  • C Introduction Examples

C Flow Control

  • C if...else
  • C while Loop
  • C break and continue
  • C switch...case
  • C Programming goto
  • Control Flow Examples

C Functions

  • C Programming Functions
  • C User-defined Functions
  • C Function Types
  • C Recursion
  • C Storage Class
  • C Function Examples
  • C Programming Arrays
  • C Multi-dimensional Arrays
  • C Arrays & Function
  • C Programming Pointers
  • C Pointers & Arrays
  • C Pointers And Functions
  • C Memory Allocation
  • Array & Pointer Examples

C Programming Strings

  • C Programming String
  • C String Functions
  • C String Examples

Structure And Union

  • C Structure
  • C Struct & Pointers
  • C Struct & Function
  • C struct Examples

C Programming Files

  • C Files Input/Output
  • C Files Examples

Additional Topics

  • C Enumeration
  • C Preprocessors
  • C Standard Library
  • C Programming Examples
  • Store Data in Structures Dynamically

C Structure and Function

C Dynamic Memory Allocation

C Struct Examples

  • Store Information of a Student Using Structure

C structs and Pointers

Before you learn about how pointers can be used with structs, be sure to check these tutorials:

  • C Pointers to struct

Here's how you can create pointers to structs.

Here, ptr is a pointer to struct .

Example: Access members using Pointer

To access members of a structure using pointers, we use the -> operator.

In this example, the address of person1 is stored in the personPtr pointer using personPtr = &person1; .

Now, you can access the members of person1 using the personPtr pointer.

By the way,

  • personPtr->age is equivalent to (*personPtr).age
  • personPtr->weight is equivalent to (*personPtr).weight
  • Dynamic memory allocation of structs

Before you proceed this section, we recommend you to check C dynamic memory allocation .

Sometimes, the number of struct variables you declared may be insufficient. You may need to allocate memory during run-time. Here's how you can achieve this in C programming.

Example: Dynamic memory allocation of structs

When you run the program, the output will be:

In the above example, n number of struct variables are created where n is entered by the user.

To allocate the memory for n number of struct person , we used,

Then, we used the ptr pointer to access elements of person .

Table of Contents

  • Example: Access struct members using pointers

Sorry about that.

Related Tutorials

  • How to Create Array of Structs in C

How to Create an Array of Structs in C Using Static Array Initialization

How to create an array of structs in c using the malloc() function.

How to Create Array of Structs in C

Creating arrays of structures in C is a fundamental aspect of programming, providing a powerful mechanism for organizing and managing complex data. In this article, we explore various methods to achieve this task, catering to different needs and scenarios.

Whether opting for the simplicity of static array initialization or the flexibility of dynamic memory allocation with the malloc() function, each approach brings its own advantages to the table.

Understanding these methods equips programmers with the knowledge to handle data efficiently and maintain code clarity in C applications.

Before diving into the array aspect, let’s review the basics of structs. A struct is a composite data type that groups variables of different data types under a single name.

This allows you to organize related information into a cohesive unit. Let’s consider a simple example using a structure named Student with integer, character array, and float members:

An array of structures in C is a data structure that allows you to store multiple instances of a structure in a contiguous block of memory. Each element of the array is a structure, and each structure contains multiple fields (or members).

This arrangement enables you to organize and manage related data in a more structured and efficient manner.

To create an array of structs, you can use static array initialization. This involves declaring an array of structs and initializing its elements at the time of declaration.

Let’s use the Student struct from the previous example:

Here, the studentRecord is an array of 5 elements where each element is of type struct Student . The individual elements are accessed using the index notation ( [] ), and members are accessed using the dot . operator.

The studentRecord[0] points to the 0th element of the array, and the studentRecord[1] points to the first element of the array.

  • The studentRecord[0].rollNumber refers to the rollNumber member of the 0th element of the array.
  • The studentRecord[0].studentName refers to the studentName member of the 0th element of the array.
  • The studentRecord[0].percentage refers to the percentage member of the 0th element of the array.

The complete program to declare an array of the struct in C is as follows.

In the C program above, we create an array of structs to represent student records.

The code begins by including the standard input/output library ( stdio.h ). Next, a structure named Student is defined, containing three members: rollNumber (integer), studentName (character array of size 20), and percentage (float).

Inside the main() function, an array of structs named studentRecord is declared and initialized with five elements. Each element corresponds to a student record and includes the student’s roll number, name, and percentage.

This initialization is done using curly braces and providing values for each member of the struct.

Subsequently, a for loop is utilized to iterate through each element of the studentRecord array. Inside the loop, the printf function is used to display the student information.

The %d placeholder is used to print the integer rollNumber , %s for the string studentName , and %.2f for the floating-point percentage . The .2f format specifier ensures that the percentage is displayed with two decimal places.

Finally, the program returns 0, indicating successful execution. The output of the program should be a clear and formatted display of the student information, presenting the roll number, name, and percentage for each student in the array.

Code Output:

Array of Structs in C - Output 1

This output demonstrates the successful creation and display of an array of structs in C using static array initialization. Each student’s information is presented clearly, showcasing the organization and accessibility of data through the combination of structures and arrays.

While static array initialization is convenient, it may not always provide the flexibility needed in certain scenarios.

Dynamic memory allocation, achieved through the malloc() function, allows us to create an array of structs with a size determined at runtime. This approach is particularly useful when dealing with variable-sized datasets.

The malloc() function is used to dynamically allocate memory. Its syntax is as follows:

Here, ptrVariable is a pointer variable of the specified cast type, and byte-size is the amount of memory to allocate in bytes. In the case of creating an array of structs, we determine the size by multiplying the number of elements by the size of each struct using sizeof .

Let’s consider an example program where we create an array of student records using dynamic memory allocation:

In this C program, dynamic memory allocation is utilized to create an array of structs representing student records. The program begins by including the necessary libraries, stdio.h for standard input/output and stdlib.h for dynamic memory allocation functions.

A structure named Student is defined to hold information about each student, including their roll number, name, and percentage. Inside the main() function, an integer variable numStudents is declared and set to 3, representing the desired number of students.

Next, a pointer to a struct Student named studentRecord is declared.

The malloc() function is then used to dynamically allocate memory for an array of structs based on the product of numStudents and sizeof(struct Student) . The cast (struct Student*) is applied to the result of malloc() to ensure that the allocated memory is treated as an array of struct Student .

A for loop is employed to iterate through each student in the dynamically allocated array. Inside the loop, the program prompts the user to input information for each student using printf and scanf functions.

The entered data is stored in the corresponding members of the studentRecord array.

After collecting the input, another for loop is used to display the student information, utilizing printf to format and print each student’s roll number, name, and percentage. The .2f format specifier ensures that the percentage is displayed with two decimal places.

Finally, the free() function is called to release the dynamically allocated memory, preventing memory leaks. The program returns 0, indicating successful execution.

Array of Structs in C - Output 2

This output demonstrates the dynamic creation of an array of structs using the malloc() function. Users can input information for the specified number of students, and the program displays the entered data.

The dynamic allocation allows for a variable number of elements and provides more flexibility in memory management.

The ability to create arrays of structs in C is an essential skill for developers working with diverse datasets. The static approach provides straightforward initialization and ease of use, while dynamic memory allocation offers flexibility when dealing with varying data sizes.

The examples provided showcase practical implementations of both methods, highlighting their strengths and use cases. As you delve into struct arrays in C, consider the specific requirements of your program and choose the method that best aligns with your coding objectives.

With these tools at your disposal, you’ll be well-equipped to navigate the complexities of data organization in C programming.

Related Article - C Array

  • How to Copy Char Array in C
  • How to Dynamically Allocate an Array in C
  • How to Clear Char Array in C
  • Array of Strings in C
  • How to Initialize Char Array in C
  • How to Print Char Array in C

Related Article - C Struct

  • Bit Field in C
  • Difference Between Struct and Typedef Struct in C
  • How to Use struct Alignment and Padding in C
  • How to Initialize Array of Structs in C
  • How to Return a Struct From Function in C
  • How to Allocate Struct Memory With malloc in C
  • C Data Types
  • C Operators
  • C Input and Output
  • C Control Flow
  • C Functions
  • C Preprocessors
  • C File Handling
  • C Cheatsheet
  • C Interview Questions

Related Articles

  • Solve Coding Problems
  • Properties of Array in C
  • Length of Array in C
  • Multidimensional Arrays in C
  • Initialization of Multidimensional Array in C
  • Jagged Array or Array of Arrays in C with Examples
  • Pass Array to Functions in C
  • How to pass a 2D array as a parameter in C?
  • How to pass an array by value in C ?
  • Variable Length Arrays (VLAs) in C
  • What are the data types for which it is not possible to create an array?
  • Strings in C
  • Array of Strings in C
  • C Library - <string.h>
  • C String Functions
  • What is the difference between single quoted and double quoted declaration of char array?
  • Array C/C++ Programs
  • String C/C++ Programs

Array in C is one of the most used data structures in C programming. It is a simple and fast way of storing multiple values under a single name. In this article, we will study the different aspects of array in C language such as array declaration, definition, initialization, types of arrays, array syntax, advantages and disadvantages, and many more.

What is Array in C?

An array in C is a fixed-size collection of similar data items stored in contiguous memory locations. It can be used to store the collection of primitive data types such as int, char, float, etc., and also derived and user-defined data types such as pointers, structures, etc.

arrays in c

C Array Declaration

In C, we have to declare the array like any other variable before using it. We can declare an array by specifying its name, the type of its elements, and the size of its dimensions. When we declare an array in C, the compiler allocates the memory block of the specified size to the array name.

Syntax of Array Declaration

where N is the number of dimensions.

c array delcaration

The C arrays are static in nature, i.e., they are allocated memory at the compile time.

Example of Array Declaration

C array initialization.

Initialization in C is the process to assign some initial value to the variable. When the array is declared or allocated memory, the elements of the array contain some garbage value. So, we need to initialize the array to some meaningful value. There are multiple ways in which we can initialize an array in C.

1. Array Initialization with Declaration

In this method, we initialize the array along with its declaration. We use an initializer list to initialize multiple elements of the array. An initializer list is the list of values enclosed within braces { } separated b a comma.

c array initialization

2. Array Initialization with Declaration without Size

If we initialize an array using an initializer list, we can skip declaring the size of the array as the compiler can automatically deduce the size of the array in these cases. The size of the array in these cases is equal to the number of elements present in the initializer list as the compiler can automatically deduce the size of the array.

The size of the above arrays is 5 which is automatically deduced by the compiler.

3. Array Initialization after Declaration (Using Loops)

We initialize the array after the declaration by assigning the initial value to each element individually. We can use for loop, while loop, or do-while loop to assign the value to each element of the array.

Example of Array Initialization in C

Access array elements.

We can access any element of an array in C using the array subscript operator [ ]  and the index value i of the element.

One thing to note is that the indexing in the array always starts with 0, i.e., the first element is at index 0 and the last element is at N – 1 where N is the number of elements in the array.

access array elements

Example of Accessing  Array Elements using Array Subscript Operator

Update array element.

We can update the value of an element at the given index i in a similar way to accessing an element by using the array subscript operator [ ] and assignment operator = .

C Array Traversal

Traversal is the process in which we visit every element of the data structure. For C array traversal, we use loops to iterate through each element of the array.

Array Traversal using for Loop

c array traversal

How to use Array in C?

The following program demonstrates how to use an array in the C programming language:

Types of Array in C

There are two types of arrays based on the number of dimensions it has. They are as follows:

  • One Dimensional Arrays (1D Array)
  • Multidimensional Arrays

1. One Dimensional Array in C

The One-dimensional arrays, also known as 1-D arrays in C are those arrays that have only one dimension.

Syntax of 1D Array in C

1d array in c

Example of 1D Array in C

Array of characters (strings).

In C, we store the words, i.e., a sequence of characters in the form of an array of characters terminated by a NULL character. These are called strings in C language.

To know more about strings, refer to this article – Strings in C

2. Multidimensional Array in C

Multi-dimensional Arrays in C are those arrays that have more than one dimension. Some of the popular multidimensional arrays are 2D arrays and 3D arrays. We can declare arrays with more dimensions than 3d arrays but they are avoided as they get very complex and occupy a large amount of space.

A. Two-Dimensional Array in C

A Two-Dimensional array or 2D array in C is an array that has exactly two dimensions. They can be visualized in the form of rows and columns organized in a two-dimensional plane.

Syntax of 2D Array in C

  • size1: Size of the first dimension.
  • size2: Size of the second dimension.

2d array in c

Example of 2D Array in C

B. three-dimensional array in c.

Another popular form of a multi-dimensional array is Three Dimensional Array or 3D Array. A 3D array has exactly three dimensions. It can be visualized as a collection of 2D arrays stacked on top of each other to create the third dimension.

Syntax of 3D Array in C

3d array in c

Example of 3D Array

To know more about Multidimensional Array in C, refer to this article – Multidimensional Arrays in C

Relationship between Arrays and Pointers

Arrays and Pointers are closely related to each other such that we can use pointers to perform all the possible operations of the array. The array name is a constant pointer to the first element of the array and the array decays to the pointers when passed to the function.

To know more about the relationship between an array and a pointer, refer to this article – Pointer to an Arrays | Array Pointer

Passing an Array to a Function in C

An array is always passed as pointers to a function in C. Whenever we try to pass an array to a function, it decays to the pointer and then passed as a pointer to the first element of an array.

We can verify this using the following C Program:

Return an Array from a Function in C

In C, we can only return a single value from a function. To return multiple values or elements, we have to use pointers. We can return an array from a function using a pointer to the first element of that array.

Note: You may have noticed that we declared static array using static keyword. This is due to the fact that when a function returns a value, all the local variables and other entities declared inside that function are deleted. So, if we create a local array instead of static, we will get segmentation fault while trying to access the array in the main function.

Properties of Arrays in C

It is very important to understand the properties of the C array so that we can avoid bugs while using it. The following are the main properties of an array in C :

1. Fixed Size

The array in C is a fixed-size collection of elements. The size of the array must be known at the compile time and it cannot be changed once it is declared.

2. Homogeneous Collection

We can only store one type of element in an array. There is no restriction on the number of elements but the type of all of these elements must be the same.

3. Indexing in Array

The array index always starts with 0 in C language. It means that the index of the first element of the array will be 0 and the last element will be N – 1.

4. Dimensions of an Array

A dimension of an array is the number of indexes required to refer to an element in the array. It is the number of directions in which you can grow the array size.

5. Contiguous Storage

All the elements in the array are stored continuously one after another in the memory. It is one of the defining properties of the array in C which is also the reason why random access is possible in the array.

6. Random Access

The array in C provides random access to its element i.e we can get to a random element at any index of the array in constant time complexity just by using its index number.

7. No Index Out of Bounds Checking

There is no index out-of-bounds checking in C/C++, for example, the following program compiles fine but may produce unexpected output when run.  

In C, it is not a compiler error to initialize an array with more elements than the specified size. For example, the below program compiles fine and shows just a Warning.

Warnings:  

Examples of Array in C

Example 1: c program to perform array input and output..

In this program, we will use scanf() and print() function to take input and print output for the array.

Example 2: C Program to print the average of the given list of numbers

In this program, we will store the numbers in an array and traverse it to calculate the average of the number stored.

Example 3: C Program to find the largest number in the array.

Advantages of array in c.

The following are the main advantages of an array:

  • Random and fast access of elements using the array index.
  • Use of fewer lines of code as it creates a single array of multiple elements.
  • Traversal through the array becomes easy using a single loop.
  • Sorting becomes easy as it can be accomplished by writing fewer lines of code.

Disadvantages of Array in C

  • Allows a fixed number of elements to be entered which is decided at the time of declaration. Unlike a linked list, an array in C is not dynamic.
  • Insertion and deletion of elements can be costly since the elements are needed to be rearranged after insertion and deletion.

The array is one of the most used and important data structures in C. It is one of the core concepts of C language that is used in every other program. Though it is important to know about its limitation so that we can take advantage of its functionality.

FAQs on C Array

1. define array in c..

An array is a fixed-size homogeneous collection of elements that are stored in a contiguous memory location.

2. How to declare an array in C?

We can declare array in C using the following syntax:

3. How do you initialize an array in C?

We can initialize an array using two methods:

  • Using Initializer list

Using Loops

Using initializer list.

We can use an initializer list to initialize the array with the declaration using the following syntax:

We can initialize an Array using Loops in C after the array declaration:

4. Why do we need Arrays?

We can use normal variables (v1, v2, v3, ..) when we have a small number of objects, but if we want to store a large number of instances, it becomes difficult to manage them with normal variables. The idea of an array is to represent many instances in one variable.

5. How can we determine the size of the C array?

We can determine the size of the Array using sizeof Operator in C. We first get the size of the whole array and divide it by the size of each element type.

6. What is the difference between Arrays and Pointers?

The following table list the differences between an array and a pointer :

Please Login to comment...

  • RishabhPrabhu
  • AnkurVineet
  • patildhanu4111999
  • akshaypawar4
  • prathamjainyt
  • nikhilpanchal
  • bharadwajramendra1
  • saurabhbombale111
  • yashkhandarepatil
  • akhilesh80025
  • mitalibhola94
  • sarajadhav12052009
  • aditiyadav20102001
  • abhishekcpp

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

404 Not found

IMAGES

  1. C Initialize Array Of Struct? The 11 Top Answers

    c assign array in struct

  2. Dynamic Array with Structs! C Tutorial 17

    c assign array in struct

  3. How to Make an Array of Structs in C

    c assign array in struct

  4. Creating an array of structs in C

    c assign array in struct

  5. How to Make an Array of Structs in C

    c assign array in struct

  6. 23. Structure

    c assign array in struct

COMMENTS

  1. Assign to array in struct in c

    2 Answers Sorted by: 14 The syntax something = { initial values } is allowed only in initializations, where an object is defined, such as: long mem [1000] = { 1, 2, 3, 4, 5, 6 }; An expression such as x = value is an assignment and cannot use the syntax for initializations.

  2. Array of Structures in C

    Array of Structures in C Read Courses When dealing with a large set of related data and different data types, organizing and managing it efficiently is crucial. In C programming, the combination of arrays and structures i.e. array of structures provides a powerful tool for managing that.

  3. Array of Structures vs Array within a Structure in C

    A 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 of different data types - int, char, float, double, etc. It may also contain an array as its member. Such an array is called an array within a structure.

  4. C struct (Structures)

    . - Member operator -> - Structure pointer operator (will be discussed in the next tutorial) Suppose, you want to access the salary of person2. Here's how you can do it. person2.salary Example 1: C structs

  5. Structure Assignment (GNU C Language Manual)

    This is the only way in C that you can operate on the whole contents of a array with one operation: when the array is contained in a struct. You can't copy the contents of the data field as an array, because r1.data = r2.data;

  6. C Programming/Pointers and arrays

    C Programming/Pointers and arrays. Pointer a pointing to variable b. Note that b stores a number, whereas a stores the address of b in memory (1462) A pointer is a value that designates the address (i.e., the location in memory), of some value. Pointers are variables that hold a memory location. There are four fundamental things you need to ...

  7. C Structures (structs)

    Structures Structures (also called structs) are a way to group several related variables into one place. Each variable in the structure is known as a member of the structure. Unlike an array, a structure can contain many different data types (int, float, char, etc.). Create a Structure

  8. How to declare, initialize and access array of structure

    Declare array of structure after structure declaration. The following code declares a student structure as we did above. After structure declaration it declares an array of student structure, capable of storing 100 student marks. // Structure declaration struct student { char name [100]; int roll; float marks; }; // Structure array declaration ...

  9. Array as Member of Structure in C

    Array as Member of Structure in C Last updated on July 27, 2020 Since the beginning of this chapter, we have already been using arrays as members inside structures. Nevertheless, let's discuss it one more time. For example: 1 2 3 4 5 6 struct student { char name[20]; int roll_no; float marks; };

  10. C Structures

    The structure in C is a user-defined data type that can be used to group items of possibly different types into a single type. ... Initialization using Assignment Operator struct structure_name str; str.member1 = value1; ... Array of Structures vs Array within a Structure in C Data Structures GeeksforGeeks. Article Tags :

  11. CS31: Intro to C Structs and Pointers

    C Stucts and Pointers. This is the second part of a two part introduction to the C programming language. It is written specifically for CS31 students. The first part covers C programs, compiling and running, variables, types, operators, loops, functions, arrays, parameter passing (basic types and arrays), standard I/O (printf, scanf), and file ...

  12. C Arrays (With Examples)

    For example, int mark [5] = {19, 10, 8, 17, 9}; You can also initialize an array like this. int mark [] = {19, 10, 8, 17, 9}; Here, we haven't specified the size. However, the compiler knows its size is 5 as we are initializing it with 5 elements. Initialize an Array Here,

  13. Array of Structures in C

    Array of Structures in C Last updated on July 27, 2020 Declaring an array of structure is same as declaring an array of fundamental types. Since an array is a collection of elements of the same type. In an array of structures, each element of an array is of the structure type. Let's take an example: 1 2 3 4 5 6

  14. C structs and Pointers (With Examples)

    C struct C Pointers to struct Here's how you can create pointers to structs. struct name { member1; member2; . . }; int main() { struct name *ptr, Harry; } Here, ptr is a pointer to struct. Example: Access members using Pointer To access members of a structure using pointers, we use the -> operator.

  15. How to Create Array of Structs in C

    Here, the studentRecord is an array of 5 elements where each element is of type struct Student.The individual elements are accessed using the index notation ([]), and members are accessed using the dot . operator.The studentRecord[0] points to the 0th element of the array, and the studentRecord[1] points to the first element of the array.. Similarly, The studentRecord[0].rollNumber refers to ...

  16. C Arrays

    Array in C is one of the most used data structures in C programming. It is a simple and fast way of storing multiple values under a single name. In this article, we will study the different aspects of array in C language such as array declaration, definition, initialization, types of arrays, array syntax, advantages and disadvantages, and many more.

  17. Assign to array in struct in c

    Assign to array is struct in c. Ask Question Asked 9 years, 4 months previously. Modified 9 years, 4 months ago. ... Arrays are non pointer (but arrays decay into pointers, understand this), the you cannot assign arrays (only initialize their, other assign struct-s containing them). You could copy that array, e.g.

  18. Assign one struct to another in C

    Assign one struct to another in C Ask Question Asked 13 years, 11 months ago Modified 2 years, 10 months ago Viewed 246k times 182 Can you assign one instance of a struct to another, like so: struct Test t1; struct Test t2; t2 = t1; I have seen it work for simple structures, bu does it work for complex structures?

  19. c++

    Assign a whole struct at once in an array Asked 11 years, 10 months ago Modified 11 years, 9 months ago Viewed 8k times 4 I am learning C++ and I have a problem with struct and arrays. My struct is: struct board { string name; string desc; int nval; int sval; int eval; int wval; }; My array looks like this: board field [10] [10];

  20. c++

    Basically, The child class contains a member as a pointer to an array of pointers to Toy objects. Now, While writing the move assign constructor , should i redirect the pointer the array members in a loop first and then delete the source object or just point the array pointer to the new Toy Child object without going through individual members?