Struct in C..
Struct is where it starts getting little bit advanced in C, let’s try to break it down to understand it in much simpler way. Struct is nothing but a user defined data type which holds all different type of data members where as on the other hand array will have only identical data members. Let’s see an example of struct.
struct name{
int member1;
float member2;
};
In defining a struct, it has to be started with struct name and the tag is optional, and a structure definition ends with a semicolon, you can also indicate a struct variable before the semicolon. Structure members can be accessed using dot operators.
Memory is allocated only when struct is defined with a variable. for example:
struct name variable; // only when an object is declared, memory is allocated
Lets see the limitations in C. struct is not object oriented like c++, all members you declare inside c is public, there is no data hiding in struct.
we cannot initialise any members inside the struct for say
struct name { int x =5 //cannot initialise this way in a struct}; because when you are declaring struct you are not allocating any memory for it.
we cannot have a function inside struct, but we can use function pointers inside struct. C struct does not support the use of operators such as +,- on struct variables.
Get Rishi Krishnan Natarajan’s stories in your inbox
Join Medium for free to get updates from this writer.
In declaring a struct we can use typedef keyword, to make it more simple.
Typedef keyword in c is used to give alias name to primitive and user defined data type. Lets see an example:
typedef struct { int a; }var;
var obj1 {.a =89};
Now let’s see about pointers in struct. pointers in struct can be used to read and write members of struct. let’s see with an example.
typedef struct{ int a; int b;}obj;
int main() {
obj first ;
int *p = (int*)&first;
p->a =9;
p->b=7;}
Here we are using pointers to access each members in a struct. let’s remember a key point here the base address of the struct is same as the base address of the first member of the structure.
Now let’s see about bit fields, bit fields are used in packaging of data types, its used when memory space is considered important. Lets see with an example:
struct var { int a :1; int b:2, int c:1}obj; //here the size of the struct variable obj is only 4 bytes. Bit fields are useful when you care about memory space.







