如何使用 C 中的结构指针打印结构中的成员数据

Bra*_*ord 2 c struct pointers

我有一个指向外部头文件中定义的 Map 类型结构的指针:

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;
Run Code Online (Sandbox Code Playgroud)

指针初始化如下:

    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.
Run Code Online (Sandbox Code Playgroud)

如何打印在 create_map 中创建的 Map 结构中存储的宽度和高度值?create_map 保存在外部文件中,它传递回 main 的唯一变量是指向映射的指针。

编译时出现以下错误(“错误:取消引用指向不完整类型的指针”)

printf("Height = %d\n", map_ptr->height);
Run Code Online (Sandbox Code Playgroud)

据我所知,指针是有效的,因为下面的代码打印了内存地址:

printf("Pointer address for map = %p\n", map_ptr);
Run Code Online (Sandbox Code Playgroud)

P.P*_*.P. 5

只需从以下位置删除struct关键字:

struct Map *map_ptr;    
Run Code Online (Sandbox Code Playgroud)

到:

Map *map_ptr;    
Run Code Online (Sandbox Code Playgroud)

您已经声明了一个无名结构并将其 typedef'ed 为Map. 因此,当您声明时struct Map *map_ptr;,编译器认为这是另一个名为 的结构Map