Initializing Structure Members to Zero in C Language
Initializing Structure Members to Zero in C Language
In C language, to initialize the members of a structure to 0, you can use curly braces {}
for initialization. The inside of the braces can be left empty, so the compiler will initialize all members of the structure to 0 (for numeric types) or a null character (for character types). For example:
#include <string.h>
struct Student {
char name[50];
int age;
float score;
};
int main() {
struct Student student1 = {0}; // All members initialized to 0 or null character
return 0;
}
Alternatively, you can use the memset
function to set all members of the structure to 0:
#include <string.h>
struct Student {
char name[50];
int age;
float score;
};
int main() {
struct Student student1;
memset(&student1, 0, sizeof(student1)); // Set all members of the structure to 0
return 0;
}
Both of these methods can initialize all members of the structure to 0.