I am curious about struct that we declare in C. What does it actually do ? I know we can make nodes & pointers to those using struct but how does it function ? Like a while loop checks the condition & branches accordingly if equal or not equal. What does struct do under the hood ?
4 Answers
A
struct
type is a user-defined composite type. It is composed of fields or members that can have different types.From
struct
-wiki:A struct in the C programming language is a declaration that defines a list of variables to be placed under one name in a block of memory, allowing the different variables to be accessed via a single pointer.
For memory allocation of a
struct
: check out How are C struct members allocated?For why to use
struct
, check out Why should we typedef a struct so often in C?

- 1
- 1

- 49,413
- 29
- 133
- 174
Its nothing more than multiple variables treated as one entity. There is not much magic behind this, the values simply appear behind each other in the order of declaration in the memory.

- 11,127
- 7
- 49
- 77
-
So in the memory the space is allocated side by side for each element in the node ? – user3181231 Jan 13 '14 at 18:03
-
@godel9 point taken, sorry for this but myself is not a native speaker – Sebastian Hoffmann Jan 13 '14 at 18:06
-
@user3181231 What is a node for you? This term is usually not used in this context. – Sebastian Hoffmann Jan 13 '14 at 18:06
-
suppose if we write struct abcd { int data; int name; } so in memory the space allocated for data & name would be side to side ? – user3181231 Jan 13 '14 at 18:07
-
@user3181231 What you wrote is a very simplistic implementation of a linked list, this basically does not have much to do with structs. In your case every node object consists of an 32bit int followed by a 32bit pointer (assuming x86 here) in memory. – Sebastian Hoffmann Jan 13 '14 at 18:11
-
Oh! thanks ! :) Now i'll delete this question as soon as possible...too much haters – user3181231 Jan 13 '14 at 18:14
A C struct
simply represents data in a specified way and doesn't do anything at all. It is used to represent a more complex data-type, such as a linked-list node.

- 12,442
- 4
- 49
- 101
Using struct a user can define its own required data type to handle complex data. just like array where all elements in array are of same type but in struct each element can be defined in user's desired way.
so struct is used to define ""user-defined data types".

- 390
- 4
- 14