Structures are a very important and useful part of C programming. They are commonly called structs, because that is how they are named in C. Structs are used to group many variable types under one name.
You define a struct as follows:
Code:
struct name {
//variables go here
}; //don't forget this semicolon!
When you define a struct, you are defining your own variable type. You can declare variables with the the struct type as follows:
Code:
struct name variable;
It's just like you would declare an int, or any other type of variable.
The variables in a struct are called members, look at this struct definition:
Code:
struct intfloat {
int a;
float b;
};
This is a very simple struct with an integer, a, and a floating point number, b. Let's say you declare the struct like this:
Code:
struct intfloat test;
To access a member from the test variable, you must use the dot operator:
This sets the member a as the number 6. You can do the same thing with member b:
This sets b as 1.5 because b is a floating point number.
Typedef is a good way to save a lot of typing. It gives a data type a new name. You can do this with the struct definition:
Code:
typedef struct {
int a;
float b;
} intfloat;
When using a typedef, you don't need to use struct for every variable you declare, just do this:
If you haven't used pointers before, please read this tutorial before moving on.
When you declare structs as pointers, you have to use the arrow operator to access members. Let's assume we already defined intfloat with a typedef, just like above:
Code:
intfloat test;
test.a=5;
test.b=4.3;
intfloat *pointer;
pointer=&test;
printf("%d, %f\n", pointer->a, pointer->b);
This code will print out:
The arrow operator is what dereferences the pointer members.
Here is an example in C that uses structs to show stock statistics:
Code:
#include <stdio.h>
typedef struct {
char *name;
float value;
float change;
} stock;
stock setval(char *name, float value, float change) {
stock temp;
temp.name=name;
temp.value=value;
temp.change=change;
return temp;
}
void printv(stock temp) {
printf("%s stats:\nStock value is:%f, Stock change is:%f\n", temp.name, temp.value, temp.change);
}
int main() {
stock google=setval("GOOG", 591.50, 2.48);
printv(google);
stock redhat=setval("RHT", 27.66, 0.53);
printv(redhat);
return 0;
}
When using structures, it is usually a good idea to have functions that make it easy to handle them. My setval function sets the statistics, my printv function prints out the stock statistics.
As always, feel free to post suggestions, questions, and positive feedback.
Remember, +rep is appreciated.
Bookmarks
Algorithms and Data Structures
Java tutorials
Algorithms Forum