Structures

Structures

C structures are special, large variables which contain several named variables inside. Structures are the basic foundation for objects and classes in C. Structures are used for:

  • Serialization of data
  • Passing multiple arguments in and out of functions through a single argument
  • Data structures such as linked lists, binary trees, and more

The most basic example of structures are points, which are a single entity that contains two variables - x and y. Let's define a point in a two-dimensional point:

struct point {
    int x;
    int y;
};
Now, let's define a new point, and use it. Assume the function  draw  receives a point and draws it on a screen. Without structs, using it would require two arguments - each for every coordinate:
/* draws a point at 10, 5 */
int x = 10;
int y = 5;
draw(x, y);
Using structs, we can pass a point argument:
/* draws a point at 10, 5 */
struct point p;
p.x = 10;
p.y = 5;
draw(p);
To access the point's variables, we use the dot . operator.

Typedefs

Typedefs allow us to define types with a different name - which can come in handy when dealing with structs and pointers. In this case, we'd want to get rid of the long definition of a point structure. We can use the following syntax to remove the  struct keyword from each time we want to define a new point:
typedef struct {
    int x;
    int y;
} point;

This will allow us to define a new point like this:

point p;
Structures can also hold pointers - which allows them to hold strings, or pointers to other structures as well - which is their real power. For example, we can define a vehicle structure in the following manner:
typedef struct {
    char * brand;
    int model;
} vehicle;
Since brand is a char pointer, the vehicle type can contain a string (which, in this case, indicates the brand of the vehicle).
vehicle mycar;
mycar.brand = "Ford";
mycar.model = 2007;



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值