Hello,
Lastly I started to work with structs (still learning this topic).
Mainly, my knowledge sources are based upon three things:
1. "C How to Program" by Deitel.
2. "Advanced C" by Hipson.
3. Google ))))
While reading Hipson's chapter on structs, I've found some part that I can't entirely understand.
Suppose we're talking about general repr. of a struct:
Code:
struct tag_name{
type member_name;
type member_name;
type member_name;
}structure_name;
So the book says:
1. If a structure_name is specified and a tag_name is
not specified, the structure is being declared but not defined.
2. If a
structure_name is
not specified and a
tag_name is specified, the structure is being defined but not declared.
3. If a structure_name and a tag_name are provided, the structure is being both defined and declared.
4. If neither a structure_name nor a tag_name is provided, a compile-time error will result.
Now assume I have a following code (just to get some example):
Code:
#include<stdio.h>
int main(void){
// case 1
struct {
int x;
int y;
}my_test;
my_test.x = 4;
my_test.y = 5;
//despite being "not defined", I get an output.
printf("x = %d, y = %d\n", my_test.x, my_test.y);
//case 2
// I define struct here:
struct my_test_2{
int a;
int b;
};
// and declare it here, by creating an instance of it named "my_var"?
struct my_test_2 my_var;
my_var.a = 15;
my_var.b = 37;
printf("a = %d, b = %d\n", my_var.a, my_var.b);
return 0;
}
I have a problem with case # 1, where my structure is declared but not defined.
When talking about functions definitions and declarations it looks pretty clear to me (hope this analogy is applicable to structs):
1. function prototype (declaration) something like: 2. 3. function definition:
Code:
int foo(int num_1, int num_2){. . . }
But what does it mean: struct that being declared but not defined?
The same question goes when "typedef" is used:
In case I write this:
Code:
typedef struct{
int x;
int y;
}my_test;
I know that typedef creates just alias names for struct this alias name is "my_test", and then in order to create an instance of it I must do the following:
Code:
my_test my_var_1;
//and only after, write the these assignment statements:
my_var_1.x = 4;
my_var_2.y = 5;
But what about struct itself, is been declared or defined such way?
Finally what is going here:
Code:
typedef struct my_test{
int x;
int y;
}my_alias;
//(is it declared/defined or both?)
I can write it in two ways:
1. my_alias my_num; (declaring variable of type struct my_test)
OR doing the same thing direct way:
2. struct my_test my_num;
Sorry for being verbose, just wanted to describe the problem.
Thanks in advance for help.
P.S. For those asking:" why didn't you use google?" The answer is simple: while googling I've found couple of sites where a explanations were exactly opposite. So I don't know where "the truth is".