How to Allocate Space for a Structure in C Programming - dummies

How to Allocate Space for a Structure in C Programming

By Dan Gookin

When the malloc() function in C programming needs exercise, it turns to the structure — one structure after another, each of them sitting in a new spot in memory, thanks to malloc(). Do they get lost? No! Because each structure keeps track of the next structure like links in a chain.

The malloc() function sets aside room for all C variable types, including arrays. It can also squeeze a structure into memory, making a nice little pocket for the thing, all referenced from a pointer.

When you fashion storage for a new structure by using a pointer, or any time you reference a structure by using a pointer, a new C operator comes into play: the -> thing, which is officially known as the structure pointer operator. This operator is the structure-pointer equivalent of the dot. Whereas the traditional structure member notation looks like this: = 14;

the same member when referenced via a structure pointer looks like this:

date->day = 14;

Why isn’t the * peeker notation used? Well, it could be. The original format for a structure member referenced from a pointer is this:

(*date).day = 14;

The parentheses are required in order to bind the * pointer operator to date, the structure pointer variable name; otherwise, the . operator would take precedence. But for some reason, primitive C programmers detested that format, so they went with -> instead.

Creating a Structured Portfolio demonstrates how a structure can be created by using the malloc() function. The structure is defined at Line 7, and a pointer variable of that structure type is declared at Line 12. In Line 15, malloc() allocates enough storage for a structure. The size of the structure is determined by using the sizeof operator.


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
 struct stock {
 char symbol[5];
 int quantity;
 float price;
 struct stock *invest;
/* Create structure in memory */
 invest=(struct stock *)malloc(sizeof(struct stock));
 puts("Some kind of malloc() error");
/* Assign structure data */
/* Display database */
 puts("Investment Portfolio");

The invest pointer references the new structure carved out of memory. Lines 23 through 25 fill the structure with some data. Then Lines 28 through 34 display the data. Carefully note how the -> operator is used to reference the structure’s members.

Exercise 1: Create a new project by using the source code from Creating a Structured Portfolio. Build and run.