简体   繁体   English

使用结构取消引用不完整类型的指针

[英]Dereferencing pointer to incomplete type using a struct

I have the following code in header "point.h": 我在标题“ point.h”中具有以下代码:

#ifndef POINT_H_INCLUDED
#define POINT_H_INCLUDED

struct Point* createDefaultValues();

#endif // POINT_H_INCLUDED

The point.c file has the following code: point.c文件具有以下代码:

#include <stdlib.h>
struct Point {
int x;
int y;
};


struct Point* createDefaultValues()
{
    struct Point* point;
    point = (struct Point*) malloc(sizeof(struct Point));
    point->x = 2;
    point->y = 1;
    return point;
};

And main.c consists of the following few lines: main.c由以下几行组成:

#include <stdio.h>
#include <stdlib.h>
#include "point.h"

int main()
{
    struct Point* cerc;
    cerc = createDefaultValues();
    printf("%d, %d", cerc->x, cerc->y);
    return 0;
}

I am getting dereferencing pointer to incomplete type error at printf() line. 我在printf()行中将指针指向不完整的类型错误。 What should i do to repair it? 我应该怎么修理?

I know i can assign default values in struct, but i don't want to do that, i want to assign them only with the function found in my header. 我知道我可以在struct中分配默认值,但是我不想这样做,我只想使用在标头中找到的函数来分配它们。

you can move the struct definition into header file: 您可以将结构定义移到头文件中:

 #ifndef POINT_H_INCLUDED
 #define POINT_H_INCLUDED

    struct Point {
      int x;
      int y;
    };


    struct Point* createDefaultValues();

    #endif // POINT_H_INCLUDED

and also include the header file in point.c 并在point.c中包含头文件

The other way around would be to write two accessor functions, so you can get values of member via them instead of deferencing pointer. 另一种方法是编写两个访问器函数,因此您可以通过它们获取成员的值,而不是延迟指针。 This approach might be better as it does not force you to place struct definition into public view. 这种方法可能更好,因为它不会强迫您将结构定义放到公众视野中。

For this, you could add intto point.h : 为此,您可以添加intto point.h

int getX(struct Point* point);
int getY(struct Point* point);

definitions go into point.c : 定义进入point.c

int getX(struct Point* point)
{
    return point->x;
}

int getY(struct Point* point)
{
    return point->y;
}

and replace it in main.c as: 并在main.c中将其替换为:

printf("%d, %d", getX(cerc), getY(cerc));

By extending this, you could write setter functions, with things like validation, etc. 通过扩展它,您可以编写带有验证等功能的setter函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM