struct data type

Thread Starter

Kittu20

Joined Oct 12, 2022
511
Hiii,

I mainly understand four data type in c language like int, char, float and double. I'm having a hard time understanding the struct data type. I understand that structure is used to store different type of variable

If int data type is written in front of a variable, it means that we can assign integer value in to variable. In the same way, if struct data type is written in front of a variable , then what does it mean?
 

MrChips

Joined Oct 2, 2009
34,630
A struct is an encapsulation of many data types into one data type.

For example, you can create an employee structure that contains:

Name
Address
Phone Number
Date of Birth
Date of Employment
Department
Room number
 

Papabravo

Joined Feb 24, 2006
22,058
An array is a data structure where each element of the array has the same data type. For example, there is an array of char, and array of double and so forth.

A struct is a generalization of an array, but the elements of a struct are not required to all be of the same data type, but they could be.

Once you can get your head around these concepts, we can talk about what a union is.
 

dl324

Joined Mar 30, 2015
18,224
If int data type is written in front of a variable, it means that we can assign integer value in to variable. In the same way, if struct data type is written in front of a variable , then what does it mean?
From K&R Second Edition:
1671898866294.png

1671898921852.png
1671900048161.png
EDIT: Add the rest of the code fragment that was on the next page...
 
Last edited:

Codemeister

Joined Dec 22, 2022
1
A data type followed by a name is a way of describing how a piece of memory should be used. A structure is just a related set of variables at consecutive member locations.
Structures are particularly good describing sets of variables that can be repeated and reused. A person structure would contain things like age and eye color, and a car structure would contain make and model and you can combine them to represent people owning cars without confusion between eye color and car model at a memory location.
I’m not sure C was the first, but it did a good job of using structures for describing how large areas of memory should be organized. It allows for compile time checking of the memory usage intentions.
The parsing and compilation of structures and other data in c is almost as complex as compiling function instructions. You can precisely describe things like sets of variables that include arrays of sets of other variables. You will get compile time errors (instead of harder to debug run time errors) if all your sections of code don’t agree with each other about how the memory should be used if they share the same structure definitions.
 
Last edited:
Top