C Struct Initialization and Character/String Fields

Common ways to initialize C structs, including char/string members.

Positional Initialization at Declaration

1
2
3
4
5
6
7
8
struct InitMember {
    int first;
    double second;
    char *third;
    float four;
};

struct InitMember test = { -10, 3.141590, "method one", 0.25f };

Order matters in positional initialization.

Assignment After Declaration

1
2
3
4
5
6
struct InitMember test;

test.first = -10;
test.second = 3.141590;
test.third = "method two";
test.four = 0.25f;
1
2
3
4
5
6
struct InitMember test = {
    .first = -10,
    .second = 3.141590,
    .third = "method three",
    .four = 0.25f
};

Notes for String Members

  • char * points to a string literal or dynamically allocated memory.
  • If writable storage is required, use char array[N] and copy content.
  • Be careful with lifetime and mutability of pointed strings.
记录并分享
Built with Hugo
Theme Stack designed by Jimmy