How to print member data from a struct using pointer to struct in C

26,999

Solution 1

Just drop the struct keyword from:

struct Map *map_ptr;    

to:

Map *map_ptr;    

You have declared a nameless struct and typedef'ed it to Map. So when you declare struct Map *map_ptr;, compiler thinks this is another struct called Map.

Solution 2

You tripped over what is called namespaces in C. There are separate namespaces for

  • typedef names, as you introduced with typedef struct { ... } Map;
  • struct tags, as you introduced with struct Map *map_ptr;
  • plus other namespaces for objects, macro names, ...

The same indentifier can be reused in different namespaces. I recommend to never bother with typedefs for structs. It only hides useful information, and all it does it saving you from writing struct every now and then. If something is a struct or pointer to a struct then I want to know it so I know whether to use -> or . to access the members. Using typedefs defeats this by hiding useful information.

One way to fix your problem is to get rid of the typedef and only use a struct tag with

struct Map {
    char *squares; //!< A pointer to a block of memory to hold the map.
    int   width;   //!< The width of the map pointed to by squares.
    int   height;  //!< The height of the map pointed to by squares.
};
struct Map *map_ptr = ...;
Share:
26,999
Bradford
Author by

Bradford

Long time student user of LaTeX. My epitaph: ``Good at APA-style tables.''

Updated on September 21, 2020

Comments

  • Bradford
    Bradford over 3 years

    I have a pointer to a struct of type Map defined in an external header file:

    typedef struct {
        char *squares; //!< A pointer to a block of memory to hold the map.
        int   width;   //!< The width of the map pointed to by squares.
        int   height;  //!< The height of the map pointed to by squares.
    } Map;
    

    The pointer is initialised as follows:

        struct Map *map_ptr;    
        map_ptr = create_map(*w_ptr, *h_ptr);
        // create_map returns Map*, w_ptr and h_ptr are pointers to height and width fields for a map/maze.
    

    How do I go about printing the values of width and height stored within the Map structure which is created in create_map? create_map is held in an external file and the only variable it passes back to main is the pointer to the map.

    The following gives an error when compiling ("error: dereferencing pointer to incomplete type")

    printf("Height = %d\n", map_ptr->height);
    

    As far as I know, the pointer is valid as the code below prints a memory address:

    printf("Pointer address for map = %p\n", map_ptr);