[英]Why am I using x->y = z instead of x.y = z in my C code?
I'm following instructions to create code for a flexible array, and I am told to use x->y = z instead of xy = z. 我正在按照说明创建用于灵活数组的代码,并被告知使用x-> y = z而不是xy = z。 What would be the reason to use pointers instead of just assigning values normally?
使用指针而不是正常分配值的原因是什么?
This code includes a custom library flexarray.h which I'll put at the bottom 这段代码包含一个自定义库flexarray.h,我将其放在底部
flexarray.c: flexarray.c:
struct flexarrayrec{
int capacity;
int itemcount;
int *items;
};
flexarray flexarray_new(){
flexarray result = emalloc(sizeof *result);
result->capacity = 2;
result->itemcount = 0;
result->items = emalloc(result->capacity * sizeof result->items[0]);
return result;
}
flexarray.h: flexarray.h:
#ifndef FLEXARRAY_H_
#define FLEXARRAY_H_
typedef struct flexarrayrec *flexarray;
extern void flexarray_append(flexarray f, int item);
extern void flexarray_free(flexarray f);
extern flexarray flexarray_new();
extern void flexarray_print(flexarray f);
extern void flexarray_sort(flexarray f);
#endif
x->y
is just syntax sugar for this x->y
只是为此的语法糖
(*x).y
Looks like flexarray
is just typedef for *flexarrayrec
, so when you write flexarray result
, compiler will "transform" it to 看起来
flexarray
只是*flexarrayrec
typedef,所以当您编写flexarray result
,编译器会将其“转换”为
flexarrayrec *result = emalloc(sizeof(flexarrayrec));
So result.capacity
, for example, would have no meaning as pointer is just a number (memory address), "it doesn't have any field". 因此,例如
result.capacity
就没有意义,因为指针只是一个数字(内存地址),“它没有任何字段”。 (*result).capacity
will work, but it's frustrating to write so many asterisks and parentheses, that's why we use ->
operator :) (*result).capacity
可以使用,但是(*result).capacity
星号和括号令人沮丧,这就是为什么我们使用->
operator :)
x->y
is equivalent to (*x).y
(it is syntactic sugar) x->y
等效于(*x).y
(它是语法糖)
That is, if x is a pointer. 也就是说,如果x是指针。 If your structure (or object) is not a pointer, you can use xy (and not x->y)
如果您的结构(或对象)不是指针,则可以使用xy(而不是x-> y)
In your case you must use dynamic allocation (pointers), since you want to use flexarray outside of the function flexarray_new(). 在您的情况下,您必须使用动态分配(指针),因为您想在函数flexarray_new()之外使用flexarray。
Your flexarray
is a pointer of struct flexarrayrec
type. 您的
flexarray
是struct flexarrayrec
类型的指针。 So- 所以-
typedef struct flexarrayrec *flexarray;
When you have structure pointer's you have to use ->
arrow operator to access structure members! 当拥有结构指针时,必须使用
->
箭头运算符来访问结构成员!
But if you have declared 但是如果你已经宣布
typedef struct flexarrayrec flexarray; // Static declaration
Now you are allowed to use .
现在您可以使用
.
dot operator to access its members! 点运算符访问其成员!
If you want to use .
如果要使用
.
means you can follow- 表示您可以遵循-
(*x).y = z instead of x->y = z;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.