【问题标题】:typedef'ed struct c, how to access instances of struct which is declared as a pointer in typedef?typedef'ed struct c,如何访问在typedef中声明为指针的struct实例?
【发布时间】: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 Vectorstruct Vector *。此外,sizeof(VectorP) 应该是sizeof(struct Vector),以便它为向量分配内存,而不仅仅是为指针(不正确)。或者更好的是,使用sizeof *p 以确保安全(以防您的类型发生变化)。此外,don't cast the return value of malloc().
  • @BLUEPIXY 他可能只想分配一个向量,而不是向量数组
  • my professor wants it that way。然后去找另一个(认真的)。
  • typedefing 指针被认为是有害的。请另找“教授”

标签: c pointers vector struct typedef


【解决方案1】:

这些行是错误的:

VectorP *p;
p = (VectorP *) malloc(DEFAULT_CAPACITY * sizeof(VectorP));

你需要改用这个:

VectorP p;
p = (VectorP) malloc(DEFAULT_CAPACITY * sizeof(struct Vector));

或者,如果您只对分配 1 个 Vector 对象而不是多个 Vector 对象的数组感兴趣:

VectorP p;
p = (VectorP) malloc(sizeof(struct Vector));

【讨论】:

  • 个人喜欢sizeof *p
  • 并且:不要强制转换 malloc() 。它无用且可能有害。
【解决方案2】:

分配应该是:

VectorP p;

p = malloc( sizeof *p );

这将为p 指向的事物之一分配足够的空间,而不管它是什么。

然后您可以通过p-&gt;sizep-&gt;items[0]p-&gt;items[1] 等访问项目。

在 C 中你应该 not cast malloc ,并且通过使用这种模式你可以避免在 sizeof 表达式中命名错误数据类型的错误。

您的结构已经包含DEFAULT_CAPACITY 项目的数组,所以我猜您只想要其中一个。如果实际分配了结构的 DEFAULT_CAPACITY 副本,那么您总共将拥有 25 个(非连续)项目。

【讨论】:

    【解决方案3】:

    你的意思好像是下面这个

    VectorP p;
    
    p = ( VectorP ) malloc( sizeof( *p ) );
    
    p->size = 0;
    

    如果你想分配一个结构数组,那么分配将如下所示

    VectorP p;
    
    p = ( VectorP ) malloc( DEFAULT_CAPACITY * sizeof( *p ) );
    
    p->size = 0;
    

    p = ( VectorP ) malloc( DEFAULT_CAPACITY * sizeof( *p ) );
    
    p[0].size = 0;
    

    或者如果你确实想分配一个指向结构的指针数组,那么代码看起来就像

    VectorP *p;
    
    p = ( VectorP * ) malloc(DEFAULT_CAPACITY * sizeof( VectorP ) );
    
    if (p == NULL)
    {
        fprintf(stderr, "Memory allocation failed!\n");
        exit(1);
    } 
    
    for ( int i = 0; i < DEFAULT_CAPACITY; i++ )
    {
        p[i] = ( VectorP ) malloc( sizeof( *p[i] ) );
    }
    
    p[0]->size = 0;
    

    【讨论】:

    • @Matt McNabb 这是一个错字。应该是 sizeof( *p )
    猜你喜欢
    • 1970-01-01
    • 2012-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-08
    • 2012-03-06
    • 1970-01-01
    相关资源
    最近更新 更多