drigoSkalWalker
drigoSkalWalker

Reputation: 2822

C initializing a array or struct, CAN I do it after the declaration?

I know, that C allow I do it.

char *array[] = {"String1", "String2",...};

but I wanna do it.

char **array or char *array[3]; array = {"String1", "String2"...};

Because I think that using a loop to fullfill a array is very bad instead initializing like a showed.

Thanks.

Upvotes: 2

Views: 1739

Answers (5)

Matthew
Matthew

Reputation: 44919

Concepts at work here: modifiable lvalue and compound literals vs. initializers.

An array is not considered a modifiable lvalue, and so the following will never work:

int i[];
int j[];
i = j;

This includes the case where the right-hand side of the assignment is a compound literal like you are using.

Compound literals look a lot like initializers but they are two different concepts with similar syntax. Initializers appear with definitions, whereas compound literals can appear in arbitrary expressions.

Since a pointer is a modifiable lvalue, you can assign a compound literal to it:

char** array;
array = (char* []) {"zero", "one", "two"};

Upvotes: 1

Friedrich
Friedrich

Reputation: 6006

The answer for Array as Jerry has given is correct it it not for a structure.

    #include <stdio.h>

struct foo {
  int v1;
  int v2;
};


int main(void){
  struct foo v1, v2;

  v1.v1 = 1;
  v1.v2 = 2;
  v2 = v1;

  printf("v2.v1 = %d, v2.v2 = %d\n", v2.v1, v2.v1);
  return 0;
}

Upvotes: 0

David Given
David Given

Reputation: 13701

Short answer: no, you can't.

When initialising a non-static array like this, the compiler has to generate code to copy the initial state of the array out of storage and into the new array. (Because it's a new array every time you call the function.) It's not actually much slower to write code to do this yourself.

Long answer: if you're willing to be evil, you can sort of do it, in C99, by wrapping the array in a struct and using structure assignment...

struct arrayWrapper
{
  char* array[4];
};

{
  struct arrayWrapper d;
  ...
  d = (struct arrayWrapper){{1, 2, 3, 4}};
}

(syntax may not be quite right.)

But that's evil, and only works in C99, so don't do it, mmm'kay?

Upvotes: 2

qbert220
qbert220

Reputation: 11556

As @Jerry says, you cannot do this for an array. Your question mentions structures, and you can do it for a structure. e.g.

struct mystruct {
   int a;
   int b;
};

struct mystruct mystruct;

mystruct = (struct mystruct){1, 2};

will assign mystruct.a to 1 and mystruct.b to 2

Upvotes: 2

Jerry Coffin
Jerry Coffin

Reputation: 490338

No -- the initialization syntax only works for initialization, not assignment, so it must be part of the array definition, not afterwards. Afterwards, what you'd have would be assigning an array instead of truly initializing it, and C does not support array assignment.

Upvotes: 3

Related Questions