Thursday, July 25, 2019

struct - Structure declaration and definition in C




If we write something like this:



typedef struct 
{
unsigned int counter;
} MyStruct;


This represents structure declaration?




Declaration says our compiler that somewhere there is a structure which have parameters of type and size like above, and no space is reserved in memory for that structure in case of declaration.



and definition is, as now we reserved a space in memory for our structure:



MyStruct tmpStruct;


Or I am wrong?



Please clarify the situation with structures.



Answer



There are different kinds of definitions in C - type definitions, variable definitions, and function definitions. Types and functions could also be declared without being defined.



Your typedef is not a declaration, it's a definition of a type. In addition to defining a struct with no tag, it defines a type name that corresponds to that struct.



A declaration of a struct would look like this:



typedef struct MyStruct MyStruct;



This would let you declare pointers to MyStruct, forward-declare functions that take MyStruct*, and so on:



void foo(MyStruct* p);


What you have is a declaration/definition of a variable of type MyStruct:



MyStruct tmpStruct;



Here is a complete example with struct's declaration separated from its definition:



#include 
// Here is a declaration
typedef struct MyStruct MyStruct;
// A declaration lets us reference MyStruct's by pointer:
void foo(MyStruct* s);
// Here is the definition
struct MyStruct {
int a;

int b;
};
// Definition lets us use struct's members
void foo(MyStruct *p) {
printf("%d %d\n", p->a, p->b);
}

int main(void) {
// This declares a variable of type MyStruct
MyStruct ms = {a:100, b:120};

foo(&ms);
return 0;
}


Demo.


No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...