这是一个完整的示例,可能有助于澄清几点:
#include <stdio.h>
#include <malloc.h>
#include <string.h>
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;
Map *
create_map ()
{
printf ("Allocating %d bytes for map_ptr, and %d bytes for map data...\n",
sizeof (Map), 100);
Map *tmp = (Map *)malloc(sizeof (Map));
tmp->squares = (char *)malloc (100);
strcpy (tmp->squares, "Map data...");
tmp->width = 50;
tmp->height = 100;
return tmp;
}
int
main(int argc, char *argv[])
{
Map *map_ptr = create_map();
printf ("map_ptr->height= %d, width=%d, squares=%s\n",
map_ptr->height, map_ptr->width, map_ptr->squares);
free (map_ptr->squares);
free (map_ptr);
return 0;
}
示例输出:
Allocating 12 bytes for map_ptr, and 100 bytes for map data...
map_ptr->height= 100, width=50, squares=Map data...
另一种方法是使用“struct Map {...}”而不是 typedef:
例子:
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.
} Map;
struct Map *
create_map ()
{
...
struct Map *tmp = (struct Map *)malloc(sizeof (struct Map));
...
}
...
struct Map *map_ptr = create_map();
printf ("map_ptr->height= %d, width=%d, squares=%s\n",
map_ptr->height, map_ptr->width, map_ptr->squares);
free (map_ptr->squares);
free (map_ptr);