• Stack Overflow Public questions & answers
  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Talent Build your employer brand
  • Advertising Reach developers & technologists worldwide
  • Labs The future of collective knowledge sharing
  • About the company

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Assign values to structure variables

A structure type is defined as:

I construct a variable of type Student and I want to assign values to it. How can I do that efficiently?

Alex Marchant's user avatar

  • 3 Unless I did not understand the question, this is a "C Basic learning" question which should be answered by itself by simply learning what C structs are and how to use them. Yet you are talking about accessing a struct instance using a unique ID. Then you should also see what "C pointers" are for that one. –  Oragon Efreet Sep 23, 2015 at 16:11

3 Answers 3

In C99 standard you can assign values using compound literals:

Alexander Ushakov's user avatar

  • 44 I can't believe nobody gives this answer until May 10, 2017. –  Nick Lee May 17, 2017 at 14:06
  • 1 So what happens if you don't specify all the parameters? For instance, say s1 is already initialized and you want to override name and score, but not id. Can you just say s1 = (Student) {.name = name, .score = score} ? Or would that overwrite id in some way? And is that behavior portable? –  gabe appleton Oct 13, 2019 at 0:44
  • 7 @gabeappleton Struct assignment always replace left side struct with the data from right side. On the right side of your sample is structure with designated initializer which missing fields will be initialized to zero by default. And then s1 will be replaced with content of new structure. So id field will be set to zero. –  Alexander Ushakov Oct 13, 2019 at 6:28
  • 1 @BobtheMagicMoose "individual assignment" here is designated initializers . It is another type of initializer than value initializer in your example. Using designated initializers we can omit values for some fields. And such initializer allows to distinguish struct init from array init which are similar in case of value initializer. In @jerico link there are designated initializers in examples for structs too. –  Alexander Ushakov Nov 24, 2020 at 19:53
  • 1 You can use any initializer type as you wish. C standard allows both of them. –  Alexander Ushakov Nov 24, 2020 at 19:54

Beware, struct and pointer to struct are 2 different things.

C offers you:

struct initialization (only at declaration time):

struct copy:

direct element access:

manipulation through pointer:

initialization function:

Pick among those (or other respecting C standard), but s1 = {id, name, score}; is nothing but a syntax error ;-)

Serge Ballesta's user avatar

Can I avoid assigning values individually?

You can if the values are already part of a similar struct , that is, you can do this:

which creates an instance of Student and initializes the fields you specify. This probably isn't really any more efficient than assigning values individually, but it does keep the code concise. And once you have an existing Student instance, you can copy it with simple assignment:

If the values are all in separate variables and you're not initializing the Student , then you'll probably need to assign the values individually. You can always write a function that does that for you, though, so that you have something like:

That'll keep your code short, ensure that the struct is populated the same way every time, and simplify your life when (not if) the definition of Student changes.

Caleb's user avatar

Your Answer

Sign up or log in, post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct .

Not the answer you're looking for? Browse other questions tagged c or ask your own question .

  • The Overflow Blog
  • Journey to the cloud part I: Migrating Stack Overflow Teams to Azure
  • Featured on Meta
  • Our Design Vision for Stack Overflow and the Stack Exchange network
  • Temporary policy: Generative AI (e.g., ChatGPT) is banned
  • Call for volunteer reviewers for an updated search experience: OverflowAI Search
  • Discussions experiment launching on NLP Collective

Hot Network Questions

  • Idiom for frustrating someone else's plans by taking what the other person wanted in the first place
  • Why is the French embassy in Niger still considered an embassy?
  • Is there any way I can recycle a device that has been iCloud locked?
  • Be big more often
  • Why is there nearly no 1x road bikes?
  • Do Killing vectors form a Lie-algebra?
  • How to put a tube in a used tubeless tire
  • Why are hangars so high?
  • In how many ways can four distinctive letters be posted in 6 post boxes such that any two go in same post box and remaining go to different boxes?
  • Are there any good alternatives to firearms for 1920s aircrafts?
  • Manned Spacecraft/Space Station design Requirements
  • Why does Canada's superficial loss rule also include a clause for "30 days before the sale"?
  • Male and female seahorses: which is which
  • What is the difference between computation and simulation?
  • Is the airport a "No Man's Land" if I remain in the plane?
  • Do neural network weights need to add up to one?
  • How can I use Windows .bat files to create folder above current folder?
  • Will a buck converter clean the power output from an automotive?
  • Why is there an indefinite article before the proper noun in "He lacked the analytic processing power of a Hamilton"?
  • Risky Surgery and resistance to slashing damage
  • How to pass a statistics exam that overly relies on memorizing formulas?
  • StarCraft II eating my RAM
  • Calculating integral with exponential function and parameter
  • Was the recent ruling against Jordan Peterson an infringement of his free speech?

c assign struct by value

Your privacy

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy .

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

C structs and Pointers

C Structure and Function

C Struct Examples

  • Add Two Complex Numbers by Passing Structure to a Function
  • Add Two Distances (in inch-feet system) using Structures

In C programming, a struct (or structure) is a collection of variables (can be of different types) under a single name.

  • Define Structures

Before you can create structure variables, you need to define its data type. To define a struct, the struct keyword is used.

Syntax of struct

For example,

Here, a derived type struct Person is defined. Now, you can create variables of this type.

Create struct Variables

When a struct type is declared, no storage or memory is allocated. To allocate memory of a given structure type and work with it, we need to create variables.

Here's how we create structure variables:

Another way of creating a struct variable is:

In both cases,

  • person1 and person2 are struct Person variables
  • p[] is a struct Person array of size 20.

Access Members of a Structure

There are two types of operators used for accessing members of a structure.

  • . - 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.

Example 1: C structs

In this program, we have created a struct named Person . We have also created a variable of Person named person1 .

In main() , we have assigned values to the variables defined in Person for the person1 object.

Notice that we have used strcpy() function to assign the value to person1.name .

This is because name is a char array ( C-string ) and we cannot use the assignment operator = with it after we have declared the string.

Finally, we printed the data of person1 .

  • Keyword typedef

We use the typedef keyword to create an alias name for data types. It is commonly used with structures to simplify the syntax of declaring variables.

For example, let us look at the following code:

We can use typedef to write an equivalent code with a simplified syntax:

Example 2: C typedef

Here, we have used typedef with the Person structure to create an alias person .

Now, we can simply declare a Person variable using the person alias:

  • Nested Structures

You can create structures within a structure in C programming. For example,

Suppose, you want to set imag of num2 variable to 11 . Here's how you can do it:

Example 3: C Nested Structures

Why structs in c.

Suppose you want to store information about a person: his/her name, citizenship number, and salary. You can create different variables name , citNo and salary to store this information.

What if you need to store information of more than one person? Now, you need to create different variables for each information per person: name1 , citNo1 , salary1 , name2 , citNo2 , salary2 , etc.

A better approach would be to have a collection of all related information under a single name Person structure and use it for every person.

More on struct

  • Structures and pointers
  • Passing structures to a function

Table of Contents

  • C struct (Introduction)
  • Create struct variables
  • Access members of a structure
  • Example 1: C++ structs

Sorry about that.

Related Tutorials

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

Create your site with Spaces

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]

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials

Top references, top examples, get certified.

C Board

  • C and C++ FAQ
  • Mark Forums Read
  • View Forum Leaders
  • What's New?
  • Get Started with C or C++
  • C++ Tutorial
  • Get the C++ Book
  • All Tutorials
  • Advanced Search

Home

  • General Programming Boards
  • C Programming

C assign value to char pointer in struct

  • Getting started with C or C++ | C Tutorial | C++ Tutorial | C and C++ FAQ | Get a compiler | Fixes for common problems

Thread: C assign value to char pointer in struct

Thread tools.

  • Show Printable Version
  • Email this Page…
  • Subscribe to this Thread…
  • View Profile
  • View Forum Posts

mothermole1 is offline

Hi, I'm having a problem assigning a value to a pointer in one of my structs This is the struct definition Code: typedef struct student *student_ptr; struct student { int ID; char *name; }; typedef struct node *node_ptr; struct node { char code[7]; char *name; int n_students; struct student students[1000]; node_ptr next; }; Here is the code using it: Code: char name; scanf("%s",&name); node->students[n].name = &name; where students is an array of student structs inside the node. The problem is that assigning name to node->students[n].name works fine, but when I call the function again to do the same thing to another student in the students array, both students have the exact same name. I have tried to scanf directly into node->students[n].name but it does not appear to scan, nor does strcpy work. I'm pretty sure that the char* in the student definition is always pointing to &name which causes all of those pointers to point to one variable. Is there a way to make each char pointer of each student point to an individual local &name? Any help would be much appreciated

JohnGraham is offline

Code: char name; scanf("%s",&name); node->students[n].name = &name; I'm surprised that doesn't segfault... you'll be stuffing however many characters you get into `name', which is a variable that can hold a single char... bound to be bad. Also, strcpy() won't work, because you need to have allocated the memory for the source, which presumably you're making the same as the destination, so it will just copy it into the same buffer, effectively doing nothing. Honestly, you might want to look a bit more into C and its string handling - are you coming from a language that does the memory management for you? Anyway, what you're safest doing is using fgets() to put input into a buffer. Put it into a static buffer in your function, then strdup() it: Code: char buf[128]; char *ret = fgets(buf, sizeof(buf), stdin); if (ret == NULL) /* deal with error */ else node->students[n].name = strdup(buf);
Thanks I came from Java The compiler has an error with the code you provided: Code: Implicit declaration of function strdup and Code: Assignment make pointer from integer without cast I'm also using the -O -Wall -ansi -pedantic flags in the compiler
Last edited by mothermole1; 04-18-2011 at 03:51 AM .
Originally Posted by mothermole1 The compiler has an error with the code you provided: Code: Implicit declaration of function strdup and Code: Assignment make pointer from integer without cast Ah, I thought strdup() was a C standard function - turns out it's a POSIX/BSD function. You can easily implement it with something like: Code: #include <stdlib.h> #include <string.h> char *strdup(const char *str) { char *new_str = malloc(strlen(str) + 1); if (new_str) strcpy(new_str, str); return new_str; }
I managed to fix the code, I used a scanf into the buf Code: scanf("%s",buf); then called strdup on buf and cast the return as char*, this seemed to clear it up Code: node->students[n].name = (char*)strdup(buf); Thank you very much!
Last edited by mothermole1; 04-18-2011 at 05:14 PM .

nonoob is offline

Yes. Code: #define MAX_NAME 50 struct student { int ID; char name[MAX_NAME + 1] }; scanf("%s", node->students[n].name); /* be sure to limit the input to length MAX_NAME somehow */
  • Private Messages
  • Subscriptions
  • Who's Online
  • Search Forums
  • Forums Home
  • C++ Programming
  • C# Programming
  • Game Programming
  • Networking/Device Communication
  • Programming Book and Product Reviews
  • Windows Programming
  • Linux Programming
  • General AI Programming
  • Article Discussions
  • General Discussions
  • A Brief History of Cprogramming.com
  • Contests Board
  • Projects and Job Recruitment

subscribe to a feed

  • How to create a shared library on Linux with GCC - December 30, 2011
  • Enum classes and nullptr in C++11 - November 27, 2011
  • Learn about The Hash Table - November 20, 2011
  • Rvalue References and Move Semantics in C++11 - November 13, 2011
  • C and C++ for Java Programmers - November 5, 2011
  • A Gentle Introduction to C++ IO Streams - October 10, 2011

Similar Threads

Struct assign values iterate string, assign a string to char pointer, how to assign ';' to a char, can't return/assign char pointer, assign value of multiple char array elements to int, tags for this thread.

View Tag Cloud

  • C and C++ Programming at Cprogramming.com
  • Web Hosting
  • Privacy Statement

Structures in C

C++ Course: Learn the Essentials

Structure in C is a user-defined data type. It is used to bind two or more similar or different data types or data structures together into a single type. The structure is created using the struct keyword, and a structure variable is created using the struct keyword and the structure tag name. A data type created using structure in C can be treated as other primitive data types of C to define a pointer for structure, pass structure as a function argument or a function can have structure as a return type.

Introduction

In C language, to store the integers, characters, and decimal values, we have int, char, float, or double data types already defined(also known as the primitive data types). Also, we have some derived data types such as arrays and strings, to store similar types of data types elements together. Still, the problem with arrays or strings is that they can only store variables of similar data types, and the string can store only characters. What if we need to store two different data types together in C for many objects? Like, there is a student variable that may have its name, class, section, etc. So if we want to store all of its information, We can create different variables for every variable like a character array to store the name, an integer variable to store the class, and a character variable to store the section. But this solution is a little messy, C provides us with a better neat and clean solution, i.e., Structure.

Why Use Structure?

Imagine we have to store some properties related to a Student like a Name, Class, and Section. We have one method to create a character array to store the Name, integer variable for Class, and character variable for Section, like:

Storing data for a single student is easy, but imagine creating that many variables for 50 students or even 500 or more. So to handle this type of problem, we need to create a user-defined data type that can store or bind different types of data types together, this can be done with the help of structure in C.

What Is a Structure?

The structure is a user-defined data structure that is used to bind two or more data types or data structures together. For storing the details of a student, we can create a structure for a student that has the following data types: a character array for storing name, an integer for storing roll number, and a character for storing section, etc. Structures don't take up any space in the memory unless and until we define some variables for it. When we define its variables, they take up some memory space which depends upon the type of the data member and alignment (discussed below).

How to Create a Structure?

To create a structure in C, the struct keyword is used followed by the tag name of the structure. Then the body of the structure is defined, in which the required data members (primitive or user-defined data types) are added.

In the above syntax, the data_members can be of any data type like int, char, double, array or even any other user-defined data type. The data_member_definition for the data types like character array, int, and double is just a variable name like name, class, and roll_no. We have also declared a variable, i.e., student1 of the Student structure. Please note that it is not mandatory to always declare structure variables in this way. We will see other ways in the coming sections.

How to Declare Structure Variables?

If we have created a Student structure for storing data of students with all the data members like student name, student class and student section, how can we use them? To use the properties of the created structure in C, we have to create structure variables. There are two ways to declare variables for structure in C language:

In the above example, Student structure is created and the student1 variable is declared for it just after the structure definition.

  • Second Way:

As we create a structure in C, we have created a user-defined data type. So this data type can be treated as the primitive data type while declaring a variable for that structure.

You can use this Online C Compiler to run your codes online.

Which Approach of Declaring Structure Variables Is Better?

If we declare the structure variables with the structure definition, they work as global variables(means they can be accessed in the whole program). If we need global variables, we can declare variables with the structure otherwise declaring it using the second approach is the best way as it is easy to maintain or initialize variables.

How to Initialize Structure Members?

Initializing a structure member means assigning values to the structure members according to their respective data types. But declaration doesn't allocate memory for the structure. When we declare a variable for a structure, only then is the memory allocated to that structure variable. Hence, assigning value to something that doesn't have memory is the same as serving food without a plate, which isn't a good idea! In short, structure members cannot be initialized during the declaration. For example:

This initialization of structure will give an error. So, how can we initialize the members then? Actually, there are three ways to initialize structure members:

  • Using dot '.' operator
  • Using curly braces ‘{}’
  • Designated initializers
  • Using Dot '.' operator

Using the dot ( . ) operator, we can access any structure member and then initialize or assign its value according to its data type.

In the above syntax first, we created a structure variable, then with the help of the dot operator accessed its member to initialize them.

Let’s take an example to understand the above syntax:

In the above code, we have created a structure, Student and declared some members in it. After that, we created an instance (variable or object of structure Student) for it to access the structure members using the dot operator and assigned value to them. Also, we used strcpy method of the string, this is used to assign the value of one string to another. In the end, we output the values of structure members with the help of the dot operator.

If we want to initialize all the members during the structure variable declaration, we can declare using curly braces.

To initialize the data members by this method, the comma-separated values should be provided in the same order as the members declared in the structure. Also, this method is beneficial to use when we have to initialize all the data members.

In the above code, first we created a structure, Student. After that, we create a variable for the structure and initialized its members using curly braces in the same order as the data members are declared inside the structure. At the end print the assigned values.

Designated initialization is simple initialization of the structure members and is normally used when we want to initialize only a few structure members, not all of them. We will discuss it in much more detail in the later section of this article.

Structures as Function Arguments

So far, we have learned the declaration, initialization, and printing of the data members of structures. Now, you must wonder how we can pass an entire structure or its members to a function. So, yes, we can do that. While passing structure as a function argument, structure variables are treated the same as variables of primitive data types. The basic syntax for passing structure as a function argument is

Let's see an example for more understanding:

In the above code, we have created a structure Student and declared some members for it to store the data of students in it. After that, we created an instance and initialized all of the structure members. There were two functions: in function printStudent() , we passed the structure by using the pass-by-value concept, while in function changeStudent() , we passed the structure by pass-by-reference.

While we are passing values by reference we get a structure pointer in the function (We will discuss structure pointers later in this article).

In C programming, memory is allocated in bits to store every data type. For example, for integer variables, 32 bits are assigned. Bit fields are the concept of Structure in C in which we can define how many bits we have to allocate to the particular data member of Structure to save memory. We can define the number of bits for a particular member using the colon (:) operator .

From the above syntax, we can see that we can change the number of bits for data members as per our requirement by using the colon operator. Let's see an example for a better understanding:

In the above code, we defined two structures for storing the dates.

  • The first structure has a size of 12 bytes. It is because there are three integer variables. Each integer variable takes 4 bytes of memory, giving the total size 3 * 4 = 12 .
  • The second structure has a size of 8 bytes. This is because, in the second structure, we defined the maximum number of bits required to represent the day and month.

Since we know that the day can have a maximum value of 31, it can be easily represented by 5 bits (2 raised to the power of 5 give us 32 , so we can store any number up to 31 in it ). Similarly, a month has a maximum value of 12 . So, it will require a maximum of 4 bits for its representation ( 2 raised to the power of 4 is 16 , which is greater than 12 ). The day and month variables both have combined 9 bits, and as they both are integers, so combined 32 bits ( 4 bytes) of memory will be allocated for them. Another 4 bytes of memory is required for the year variable. Hence, the total size is 4 + 4 = 8 bytes.

We can observe that both structures have the same number of data members, but the second one takes less space. So by defining the maximum number of bits, we can save memory.

Accessing Structure Elements

We can directly access the structure member using the dot(.) operator. The dot operator is used between the structure variable name and the structure member name we want to access. Let’s see the syntax to understand it in a better way.

Here we created a simple structure, Complex to define complex numbers. We created a structure variable var and accessed its structure members: real and imaginary with the help of dot operator and assigned them some value. After that, we printed the values using the dot operator again.

What Is Designated Initialization?

Designated initialization is simple initialization of the structure members and is normally used when we want to initialize only a few structure members, not all of them.

From syntax, we can see that we use curly braces, and in between them, with the help of the dot operator, data members are accessed and initialized. There can be any number of structure members from a single structure that we can initialize, and all of them are separated using commas. But the most important thing is that we can initialize members in any order. It is not compulsory to maintain the same order as the members are declared in the structure.

In the above example, we can see that we have initialized only two members of the structure. Also, note that they are not initialized in the order as they were declared in the structure.

What Is an Array of Structures?

When we create an array of any primitive data type with size five, do you know what happens? An array consisting of 5 memory blocks is created, and each block works the same way as a single variable of the same data type. As a structure in C is a user-defined data type, we can also create an array of it, same as other data types.

From the above syntax, we created an array of structures with each memory block storing a single structure variable.

In the above code, we have created a structure and then an array of size 5 to store five structure elements. After that, we accessed structure members using array index to take input or assign values. We can pass an array of structures as a function argument as well.

For example:

In the above code, we have created a structure, Student, and then an array, arr of size 5 to store five structure elements. After that, we accessed structure members using array index to take input or assign values. We created a function, print() , that takes two parameters: an array of structure and size of the array. In this function, we printed all the values of each array block.

Nested Structures

The nested word means placed or stored one inside the other. As the structure in C is a user-defined data type so while creating a structure, we can define another structure as its data member, which leads to a structure with another structure inside it. Even the nested structure can have its nested structure.

In the above syntax, structure_1 is defined first then nested into another one, i.e., structure_2 .

In the above syntax, we defined the structure_1 inside the structure_2 . As we create a structure inside another one, we can define variables for this structure as we normally define for the structures.

To initialize the structure variables either we can access every data member using a simple dot operator or if we are going to initialize using curly braces, then we have to maintain the same order of data members as they were defined in the structure so for nested structure members also maintain the order, as we initialized variable v1 in above example.

In the above example, we have created a structure, Student with a nested structure, Address inside it. We initialized the data members of the Student structure variable at the end of the structure. Two more structures are created: Subject and Teacher . Subject structure is nested in Teacher Structure. In the main function, we created a variable for Teacher , took user input for all its members, and then printed them using the printf() statements. There can be two ways to create nested structures. The first way is to create a structure (like Subject) and add it to another structure (like Teacher) as a data member or define the structure (like Address) inside another structure (like Student).

Use of typedef in Structure

The typedef is a keyword in the C language used to give an alias to a data type, any syntax, or a part of code. The primary purpose of typedef is to make code short, increasing the code's readability. To declare a structure variable, we write struct keyword first, then structure name, and then the variable name, which is a little long. To give a short name to the structure, we can use typedef. Let’s see the syntax to understand precisely how it works:

We have defined two ways to use typedef with structure in the above syntax. In the first case, we have typedef the structure after declaring it, while in the second, the structure has been typedef during declaration. Also, new_name could be the same as structure_name . For example:

We have created a structure, Complex in the above code and declared it with typedef using both of the syntaxes discussed. So, essentially, we have two aliases for struct Complex, i.e., Complex and c . In the main function, we declared three structure variables for the same structure using three different ways. First, we declared in a general way. Second, we declare using Complex alias and lastly using c alias. At last, we assigned some values to this and then printed them all.

What Is a Structure Pointer?

A pointer is a variable that stores the address of another variable. As a structure consists of some data types or data structures for which memory is allocated to the structure variable, we can use a structure pointer to store the address of that memory. A structure pointer is essentially a pointer to a structure variable. Please note that we use the arrow operator (->) to access the structure member using a pointer.

In the syntax above, we first declared a structure variable and then a structure pointer pointing to that variable.

In the above code, we first created a structure, Complex, to store the real and imaginary values of a complex number. We also declared a structure variable, c , and initialized its data members. Then in the main() function, we created a pointer, cptr of Complex type, and assigned it the address of structure variable, c . Thereafter, we accessed structure members using the arrow operator and assigned them values. In the end, we printed the values of data members using the arrow operator.

What Is Structure Member Alignment?

As soon as a structure variable is declared, we know that memory is allocated to it according to the variable's data type. A structure consists of different data members, so if they are not aligned properly, there will be memory wastage. To reduce the memory waste by the random declaration of data members, we give them proper alignment (i.e., proper order) by defining them in decreasing order of their memory size.

We have declared two structures in the above code, and both have the same data members. The only difference is in their order of declaration. The first structure has the size of 32 bytes, while the second has 24 bytes due to alignment only. So, to reduce memory loss, while declaring a structure, always declare the data members in decreasing order of memory size requirement.

C Structures Limitations

Structures in C have many limitations as compared to other user-defined data types in other languages. Structures in C does not provide the data hiding property(by which we can make some members private and they cannot be accessed from outside of structure) and every member of the structure can be accessed. We cannot define functions inside the Structures in C, so there is no constructor and as structures do not have their own memory so we cannot ever initialize our data members inside it. If the alignment of the Structure members is not correct then they may cause some loss of memory.

  • Structure in C is a user-defined data type. It binds the two or more data types or data structures together.
  • The Structure is created using struct keyword and its variables are created using struct keyword and structure name.
  • A data type created using structure in C can be treated as other primitive data types of C to declare a pointer for it, pass it as a function argument, or return from the function.
  • There are three ways to initialize the structure variables: using the dot operator, using curly braces, or designated initialization.
  • One structure can consist of another structure, or more means there can be nested Structures.
  • With the help of typedef, we can give short or new names to a structure data type.

Aticleworld

Aticleworld

Aticleworld offer c tutorial,c programming,c courses, c++, python, c#, microcontroller,embedded c, embedded system, win32 api, windows and linux driver, tips, pointers as member of structure in c.

pointers as member

A pointer could be a member of structure , but you should be careful before creating the pointer as a member of structure in C. Generally we take a pointer as a member when we don’t know the length of the data which need to store.

Let’s see an example to the better understanding,

The above structure “Info” contains two members, integer variable (iLen) and a pointer to the character (pcName).

How to access pointer member of structure in C

Similar to another members pointer member is also access by the structure variable or pointer with the help of dot ( . ) or arrow ( -> ) operator. The left (first) operand of the  operator  should be variable of structure or pointer to the structure and right (second) operand shall name of a pointer member that you want to access.

See the below code, in which we are creating a structure variable and initializing the variable with literal string and their length. We are also assigning the address of the structure variable (MyInfo) to the pointer to the structure (ptrMyInfo).

pointer as member in structure

If you like the video course, you can check this course created by my friends Kenny Kerr. The course contains video lectures of 4.13-hour length covering all basic topics of c language.

How to assign a value to a pointer member of structure in C

Before assigning a value to a pointer you should assign a valid memory. If you don’t assign a valid memory, you will get the undefined behavior. There is two way to access the value of a pointer member of a structure in C.

1.  Using the structure variable

pointer as member

How does the above program work?

In the above program, MyInfo is a structure variable. Using the MyInfo we can access the members of the structure piData and pcName. As we know that we have to provide a valid memory to the pointer before assigning a value, so here I am using the malloc ( memory management function ) to allocate heap memory for the pointers.

After the allocation of the memory, I am copying the data in piData and pcName and displaying the copied data on the console using the printf.

2.  Using the pointer to the structure

Similar to the structure variable you can access the pointer member using the pointer to structure. But the difference is that when you are going to access using the pointer to structure you should assign memory to the pointer. See the below example code.

Recommended Posts for you

  • How to access pointer inside a structure in C?
  • Create a students management system in C.
  • Create an employee management system in C.
  • Top 11 Structure Padding Interview Questions in C
  • structure in C: you should know in depth
  • What is flexible array member in c?
  • What is importance of struct hack in c?
  • How to use the structure of function pointer in c language?
  • Function pointer in structure.
  • Pointer Arithmetic in C.
  • Memory Layout in C.
  • Union in C, A detailed Guide.
  • typedef vs #define in C.
  • Macro in C, with example code.
  • enum in C, you should know.
  • You should know the volatile Qualifier.
  • 100 C interview Questions.
  • Interview questions on bitwise operators in C.
  • A brief description of the pointer in C .
  • Dangling, Void, Null and Wild Pointers
  • 10 questions about dynamic memory allocation.
  • File handling in C.
  • Pointer in C .
  • C language character set .
  • Elements of C Language .
  • Data type in C language.
  • Operators with Precedence and Associativity in C .
  • C format specifiers.
  • C++ Interview Questions.

You might also like

strcat feature in C

How to use and Implement own strcat in C

How to use islower function in c programming, what is the difference between char array and char pointer in c.

Difference between malloc and calloc (malloc vs calloc)

Difference between malloc and calloc (malloc vs calloc)

Leave a reply cancel reply.

Your email address will not be published. Required fields are marked *

Save my name, email, and website in this browser for the next time I comment.

c assign struct by value

Q: Assigning values to const struct*

Magnus Ingvarsson's profile photo

Magnus Ingvarsson

Tanmoy Bhattacharya's profile photo

Tanmoy Bhattacharya

|> If I use (pointer->element = value) to assign values to a |> struct *pointer, is there any good way of assigning the |> values of this struct to the const struct* ? memcpy() ?

Scott McKellar's profile photo

Scott McKellar

IMAGES

  1. C Structure

    c assign struct by value

  2. Structure in C Program with Examples

    c assign struct by value

  3. Sort Linked list C++

    c assign struct by value

  4. Structures and pointers in C

    c assign struct by value

  5. C Programming Tutorial 70 Pointers to Structures

    c assign struct by value

  6. Structure in C Program with Examples

    c assign struct by value

VIDEO

  1. Advanced C++

  2. 155 ABAP Programming Database Operations DELETE Part2

  3. Difference between struct and class in C#

  4. Assign Expenses to a Customer or Project 7310 Xero 2022 -2023

  5. SQL Interview Questions and Answers Part-1

  6. Getting Started with Citrix XenApp 6.5 Tutorial: Printing and Printing Drivers

COMMENTS

  1. What Are RVU Values by CPT Code?

    A relative value unit based on a Current Procedural Terminology code assigns a standard work value based on a medical procedure performed by health care providers, according to Advancing the Business of Healthcare. The RVU represents the co...

  2. What Are the Baseball Cards with the Highest Values of All Time?

    Baseball cards were first printed in the 1860s, but their first surge in widespread popularity didn’t occur until the turn of the 20th century. PSA, a world-renowned third-party authentication company, assigns a grade of 1 to 10 in determin...

  3. What Is the Abbreviation for “assignment”?

    According to Purdue University’s website, the abbreviation for the word “assignment” is ASSG. This is listed as a standard abbreviation within the field of information technology.

  4. Assign values to structure variables

    @gabeappleton Struct assignment always replace left side struct with the data from right side. On the right side of your sample is structure

  5. Structures in C++

    in the aggregrate, you can later assign values to any data fields using the dot (.)

  6. C struct (Structures)

    Notice that we have used strcpy() function to assign the value to person1.name .

  7. C Structures (structs)

    An error will occur: prog.c:12:15: error: assignment to expression with array type.

  8. Why can we not assign values to variables inside the structure of C?

    The only reason we can not assign value to variables inside structure is due to it's definition. structure is a definition and not a declaration.

  9. How to Assign One Structure to Another

    In this video lesson we will see we can assign value of one structure variable ... Assigning value of one structure variable to another in C

  10. C assign value to char pointer in struct

    C assign value to char pointer in struct. Hi, I'm having a problem assigning a value to a pointer in one of my structs. This is the struct

  11. Structures in C

    When we declare a variable for a structure, only then is the memory allocated to that structure variable. Hence, assigning value to something that doesn't have

  12. Assign values in structure in c

    WebOct 15, 2016 · How to assign value to Struct properties in C Ask

  13. Pointers as Member of Structure in C

    Before assigning a value to a pointer you should assign a valid memory. If you don't assign a valid memory, you will get the undefined behavior. There is two

  14. Q: Assigning values to const struct*

    assigned to the pointer all at once because it's a constant. If I use (pointer->element = value) to assign values to a struct *pointer, is there