0

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.

2
  • user3758232 Do you want all strings the same size? Commented Jun 20, 2020 at 1:35
  • Yes, that's what I meant by fixed-size. Commented Jun 22, 2020 at 17:54

1 Answer 1

2

Simplest is:

char data[2][4] = {"abc", "def"};
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.