Unusual struct in c

Viewed 139

how should I understand the array of two strings?

static struct S1 {
    char c[3], *s;
} s1 = {"abc", "def" };

Probably the question is not correct but I have difficulties to understand how it works

4 Answers

S1.c has space for 3 bytes and S1.s is a pointer to a string.

the first part defines the structure:

struct S1 {
    char c[3], *s;
};

The next part creates an instance of this type and initializes it with a few values:

static struct S1 s1 = {"abc", "def" };

static is not part of the struct definition. It refers to the visibility of the instance variable.

The first initialiser "abc" copies those 3 characters into the member char c[3]. There is no room for a string terminator so it is a simple array and cannot be treated as a string.

The second initialiser "def" copies a pointer into the member char *s. It points to the string literal "def" which is placed in read-only memory. It can be treated as a string but cannot be modified.

The initializer {"abc", "def" } is not an array. In this context, it is used to initialize an instance of the struct.

This is not the same code, but might help to understand what is going on, 1st of all it not array. The structure have 2 elements.

#include <stdio.h>

struct S1 {
    char c[3];
    char* s;   
};

int main(void) {
    struct S1 s1 = { .c = "abc", .s = "def" };
    printf("s1.c: %.*s\n", 3, (char*) s1.c);
    printf("s1.s: %s\n", s1.s);
}
Related