1

Given this struct :

typedef struct test {
  char field1[20];
  char *field2;
} test_s

How can initialize this kind of structure with a designated initializer, knowing that I want field2 to point to field1 ?

test_s test = {.field1[0] = '\0', .field2 = .field1};

doesn't work.

2
  • gcc.gnu.org/onlinedocs/gcc/Designated-Inits.html Commented Jul 24, 2017 at 9:25
  • 1
    @rsp Maybe I misread something, but there not a clue that you can do "varName.designator". In fact, I read nothing usefull for my situation. For what purpose did you link this manual ? Commented Jul 24, 2017 at 9:55

1 Answer 1

5

In case of a single-item declaration you can use the name of the variable being declared, because the compiler can take address at any time during initialization:

test_s test = {.field1[0] = '\0', .field2 = test.field1};

Demo.

Sign up to request clarification or add additional context in comments.

8 Comments

And what if I can't know the name of the variable ?
@Tom's What would be the context for that?
#define TEST_CONSTRUCTOR {.field1[0] = '\0', .field2 = .field1} used like test_s varname = TEST_CONSTRUCTOR. I know that i can do #define TEST_CONSTRUCTOR(varName) {.field1[0] = '\0', .field2 = varName.field1} but I wonder if not passing the variable name is possible.
@Tom's I tried a few things, but I can't think of an elegant way around passing variable name to your macro.
Thanks, it's logic I suppose. I will passing the variable name in my macro and be happy that a solution exist. Thank you !
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.