【发布时间】:2014-10-29 19:38:13
【问题描述】:
这是我的代码:
#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。 -
首先,将指针隐藏在 typedef 后面是一个可怕的想法。如果我是你,我会使用
struct Vector和struct Vector *。此外,sizeof(VectorP)应该是sizeof(struct Vector),以便它为向量分配内存,而不仅仅是为指针(不正确)。或者更好的是,使用sizeof *p以确保安全(以防您的类型发生变化)。此外,don't cast the return value ofmalloc(). -
@BLUEPIXY 他可能只想分配一个向量,而不是向量数组
-
my professor wants it that way。然后去找另一个(认真的)。 -
typedefing 指针被认为是有害的。请另找“教授”
标签: c pointers vector struct typedef