Amaterastis
Amaterastis

Reputation: 479

Initialisation of pointer to structure using field elements

I was wondering if it is possible in C to initialise a structure in a following way:

struct Test* test = { .int_value = 10, .char_value = 'c', .pointer_to_float_value = (float*)1.512 };

If I try to do this with a structure defined in a way:

struct Test
{
    int int_value;
    char char_value;
    float* pointer_to_float_value;
};

I get an error for all elements of the structure:

error: field name not in record or union initializer

Is there a way to bypass this issue?

Upvotes: 2

Views: 397

Answers (3)

nielsen
nielsen

Reputation: 7594

It is indeed possible, but you are declaring a pointer to a struct and trying to initialize it as a struct (not pointer). The same issue with the pointer to float. The following should work:

    float a = 1.512;
    struct Test test_struct = { .int_value = 10, .char_value = 'c', .pointer_to_float_value = &a };
    struct Test *test = &test_struct;

Upvotes: 3

4386427
4386427

Reputation: 44274

There are a number of problems with your code. You don't have a = sign and you are not handling pointers and types correctly.

It can be done like:

struct Test * test = &(struct Test){ .int_value = 10, 
                                     .char_value = 'c',
                                     .pointer_to_float_value = &(float){1.512f} };

Notice how it uses (struct Test) to set the type of the compound literal and & to get a pointer to it. The same applies to the float pointer.

Upvotes: 1

Vlad from Moscow
Vlad from Moscow

Reputation: 310970

This syntax

struct Test* test { .int_value = 10, .char_value = 'c', .pointer_to_float_value = (float*)1.512 };

is invalid.

Instead you could use a compound literal as for example

float f = 1.512f;
struct Test* test = &( struct Test ){ .int_value = 10, .char_value = 'c', .pointer_to_float_value = &f };

From the C Standard (6.5.2.5 Compound literals)

5 The value of the compound literal is that of an unnamed object initialized by the initializer list. If the compound literal occurs outside the body of a function, the object has static storage duration; otherwise, it has automatic storage duration associated with the enclosing block.

Upvotes: 3

Related Questions