c指向结构问题的指针 [英] c pointer to struct issue
问题描述
以下代码在倒数第二条语句中的箭头处给我一个错误.我不知道为什么会这样.有人可以告诉我为什么吗?
The following code is giving me an error at the arrow in the second to last statement. I have no idea why this is . Could someone please tell me why?
我什至不知道从哪里开始.我以为是正确的,但是有一些问题.
I have no idea where to even begin. I thought it is correct but there is some issue.
/*
* 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);
}
推荐答案
您使用了错误的运算符,您的struct DynArr
实例不是指针,因此必须使用.
运算符.
You are using the wrong operator, your instance of struct DynArr
is not a pointer, hence you must use the .
operator.
struct DynArr da;
/* This is also wrong because `capacity' has not been initialized yet! */
assert(da.capacity > 0);
/* ^ it's not a poitner */
,其他所有情况都相同.
and in all the other cases the same.
当实例是struct的Poitner时,例如
When the instance is a poitner of struct, like
struct DynArr da;
struct DynArr *pda;
pda = &da;
pda->capacity = 0;
/* ^ it's correct here */
编辑:
您编辑完问题后,我可以看到问题了
After you edited your question I can see the problem
if(da->data[0]->key == 2)
da->data
的类型为TYPE *
,并且您正在取消指向da->data[0]
中第一个元素的指针,因此它不再是TYPE *
类型的指针,即不再是指针,因此您需要
da->data
is of type TYPE *
and you are dereferencing a pointer to it's first element in da->data[0]
, so it's no longer of type TYPE *
i.e. not a pointer, so you need
if(da->data[0].key == 2)
这篇关于c指向结构问题的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!