这里是我的代码:typedef'ed struct c,如何访问在typedef中声明为指针的struct实例?
#include <stdio.h>
#define DEFAULT_CAPACITY 5
typedef struct Vector
{
int items[DEFAULT_CAPACITY];
int size;
} *VectorP;
// I am not allowed to change this struct definition.
int main()
{
VectorP *p;
p = (VectorP *) malloc(DEFAULT_CAPACITY * sizeof(VectorP));
if (p == NULL)
{
fprintf(stderr, "Memory allocation failed!\n");
exit(1);
}
//The problem is that I can't access instance of the vector this way ->
p->size = 0;
}
网上搜索,我发现,这是事做VectorP
已经是一个指针,因为我的教授希望这样的说法我不能改变这一点。我该如何解决这个问题?
'VectorP'只是'struct Vector *'的别名。所以'VectorP * p'是一个指向'struct Vector'指针的指针。如果你想要一个指向结构的指针,只需使用'VectorP'。 – clcto 2014-09-04 22:27:56
首先,在typedef后面隐藏指针是一个可怕的可怕想法。如果我是你,我只需要使用'struct Vector'和'struct Vector *'。另外,'sizeof(VectorP)'应该是'sizeof(struct Vector)',这样它就可以为向量分配内存,而不仅仅是指针(不正确)。或者甚至更好,为了安全起见,使用'sizeof * p'(以防你的类型改变)。此外,[不要转换'malloc()']的返回值(https://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc/605858#605858)。 – 2014-09-04 22:32:40
@BLUEPIXY他大概只想分配一个矢量,而不是一个矢量数组 – clcto 2014-09-04 22:38:48