Open In App

How to Initialize Char Array in Struct in C?

Last Updated : 08 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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




// C program to initialize char array in struct
  
#include <stdio.h>
#include <string.h>
  
// defining struct name person
struct Person {
    // creating char array in struct
    char Name[50];
};
  
int main()
{
  
    //// Initialize the struct with a name and age
    struct Person person1 = { "Jack" };
    struct Person person2;
    
    // initialization after delcaration
    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

Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads