user3758232
user3758232

Reputation: 882

Stack-allocated array of fixed-size strings

I want to build an array of constant, fixed size strings. I could use malloc if I had to, but I am still learning C and I want to understand why my static approach below is not valid:

typedef char Str[4];

const Str a = "abc";
const Str b = "def";

const Str data[2] = {a, b};

GCC gives me

warning: initialization of ‘char’ from ‘const char *’ makes integer from pointer without a cast [-Wint-conversion]
   10 | const Str data[2] = {a, b};
      |                      ^```

and

error: initializer element is not computable at load time

Why is the compiler saying that the first element of the array is char instead of const Str alias constant char[4]?

Any help is appreciated. Thanks.

EDIT: I found out that using const char *data[2] = {...} works. I guess it has to do with the several constraints that come with arrays, which I am still grappling with and that can most times be resolved using pointers.

Upvotes: 0

Views: 198

Answers (1)

stark
stark

Reputation: 13189

Simplest is:

char data[2][4] = {"abc", "def"};

Upvotes: 2

Related Questions