【问题标题】:c pointer to struct issuec 指向结构问题的指针
【发布时间】:2015-05-26 23:47:35
【问题描述】:

以下代码在倒数第二个语句中的箭头处给我一个错误。我不知道为什么会这样。谁能告诉我为什么?

我什至不知道从哪里开始。我认为这是正确的,但有一些问题。

      /* 
 * File:   newmain.c
 * Author: user1
 *
 * Created on May 26, 2015, 4:30 PM
 */

#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
/*
 * 
 */


#ifndef KEYTYPE
#define KEYTYPE      char *
#endif

#ifndef VALUETYPE
#define VALUETYPE     double
#endif

#ifndef TYPE
#define TYPE struct association
//# define TYPE int
#endif

struct association
{

    KEYTYPE key;
    VALUETYPE value;

};

struct DynArr
{
    TYPE *data;     /* pointer to the data array */
        //struct association *data;
    int size;       /* Number of elements in the array */
    int capacity;   /* capacity ofthe array */
};


int main(int argc, char** argv) {

    struct DynArr *da;
    da = malloc(sizeof(struct DynArr));


    assert(da!= 0);
    da->capacity = 2;
    da->data = malloc(sizeof(TYPE) * da->capacity);
    assert(da->data != 0);
    da->size = 0;


    if(da->data[0]->key == 2) //test.c:58:10: error: invalid type argument of ‘->’ (have ‘struct DynArr’)    <<<<<<<<<<<<<<<<<<

    return (EXIT_SUCCESS);
}

【问题讨论】:

  • 你键盘上的typedef按钮坏了吗?

标签: c pointers struct


【解决方案1】:

您使用了错误的运算符,struct DynArr 的实例不是指针,因此您必须使用 . 运算符。

struct DynArr da;
/* This is also wrong because `capacity' has not been initialized yet! */
assert(da.capacity > 0); 
      /* ^ it's not a poitner */

在所有其他情况下都一样。

当实例是struct的指针时,比如

struct DynArr  da;
struct DynArr *pda;

pda = &da;
pda->capacity = 0;
 /* ^ it's correct here */

编辑

编辑问题后,我可以看到问题

if(da->data[0]->key == 2)

da-&gt;dataTYPE * 类型,并且您正在取消引用指向它在 da-&gt;data[0] 中的第一个元素的指针,因此它不再是 TYPE * 类型,即不是指针,所以您需要

if(da->data[0].key == 2)

【讨论】:

  • 它给出了与指针相同的错误。我做了一个简单的例子,看看我是否可以在这里发布它,但在原始问题中它使用的是指针。我修改了代码以使用指针,它仍然给出了同样的东西。
  • 你不应该发布 simplified 代码示例,除非它重现问题我很抱歉粗鲁,我现在将删除该评论。
猜你喜欢
  • 1970-01-01
  • 2017-01-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-14
相关资源
最近更新 更多