Search⌘ K
AI Features

Initialize Compound Types with `0`

Understand how to initialize compound types such as structs and arrays in C safely and portably by using zero initialization. Learn why memset is unsafe for these types, and how zero initialization and memcpy provide reliable and maintainable solutions that simplify resetting values without risking undefined behavior.

We'll cover the following...

Problem Context

Virtually every coding standard bans uninitialized variables, and for very good reason. Initializing a basic type such as int or char is straightforward, but what is the correct way of initializing a compound type like an array or struct? A dangerous but unfortunately common practice is shown below:

C
#include<stdio.h>
#include<string.h>
struct TemperatureNode
{
double todaysAverage;
struct TemperatureNode* nextTemperature;
};
int main() {
struct TemperatureNode node;
memset(&node,0, sizeof node);
printf("Node created\n");
return 0;
}

The problem is that memset, as its name indicates, sets the bits to the given value and ...