Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

461
Views
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?

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

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;
over 4 years ago · Santiago Trujillo Report

0

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.

over 4 years ago · Santiago Trujillo Report

0

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.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!