Randomblue
Randomblue

Reputation: 116263

Issue initialising a struct

This is my code:

typedef struct{
  char name[64];
} Cat;

Cat createCat(char name[64]) {
  Cat newCat;

  int i;

  for(i = 0; i < 64; i += 1) {
    newCat.name[i] = name[i];
  }

  return newCat;
}

Cat exampleCat = createCat("Bob");

It compiles with the following error:

initializer element is not constant

What am I doing wrong?

Upvotes: 3

Views: 115

Answers (3)

Bo Persson
Bo Persson

Reputation: 92211

You really don't need to write a function to initialize a struct. You can just use an initializer where you give values to each member (only one here).

Cat exampleCat = {"Bob"};

Also note that if you instead had used C++, you would have the option of using a dynamic initializer, and the code would be ok.

Upvotes: 2

Ry-
Ry-

Reputation: 224858

Cat exampleCat = createCat("Bob");

You can't do a method call here. Initialize exampleCat somewhere else.

This is explained in the spec, section 6.7.8/4:

All the expressions in an initializer for an object that has static storage duration shall be constant expressions or string literals.

Upvotes: 6

Wug
Wug

Reputation: 13196

Try instead:

void createCat(Cat * kitty, char name[64]) {
  int i;

  for(i = 0; i < 64; i += 1) {
    kitty->name[i] = name[i];
  }
}

Cat exampleCat;
createCat(&exampleCat, "Bob");

Upvotes: 0

Related Questions