简体   繁体   中英

Dereferencing pointer to incomplete type using a struct

I have the following code in header "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:

#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:

#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. 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.

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

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 :

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

definitions go into 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:

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

By extending this, you could write setter functions, with things like validation, etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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