How to Initialize Char Array in Struct in C?
Last Updated :
08 Feb, 2024
In C++, we can also define a character array as a member of a structure for storing strings. In this article, we will discuss how to initialize a char array in a struct in C.
Initialization of Char Array in Struct in C
When we create a structure instance (variable) in C that includes a char array, we can set an initial value for that char array directly using the list initialization.
Syntax
struct StructName structVariable = { "string value"};
But we can only initialize using this method in the declaration of the variable. If we initialize them after declaration, we have to use the strcpy() function.
C Program to Initialize Char Array in Struct
The below example demonstrates the initialization of a char array in structure.
C
#include <stdio.h>
#include <string.h>
struct Person {
char Name[50];
};
int main()
{
struct Person person1 = { "Jack" };
struct Person person2;
strcpy (person2.Name, "Roman" );
printf ( "Person 1 Name: %s\n" , person1.Name);
printf ( "Person 2 Name: %s\n" , person2.Name);
return 0;
}
|
Output
Person 1 Name: Jack
Person 2 Name: Roman
Share your thoughts in the comments
Please Login to comment...