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

467
Views
Inicialización de puntero a estructura usando elementos de campo

Me preguntaba si es posible en C inicializar una estructura de la siguiente manera:

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

Si trato de hacer esto con una estructura definida de una manera:

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

Me sale un error para todos los elementos de la estructura:

 error: field name not in record or union initializer

¿Hay alguna manera de evitar este problema?

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

De hecho, es posible, pero está declarando un puntero a una estructura e intentando inicializarlo como una estructura (no como un puntero). El mismo problema con el puntero para flotar. Lo siguiente debería funcionar:

 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

esta sintaxis

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

es inválido.

En su lugar, podría usar un literal compuesto como, por ejemplo

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

Del Estándar C (6.5.2.5 Literales compuestos)

5 El valor del literal compuesto es el de un objeto sin nombre inicializado por la lista de inicializadores. Si el literal compuesto se encuentra fuera del cuerpo de una función, el objeto tiene una duración de almacenamiento estática; de lo contrario, tiene una duración de almacenamiento automático asociada con el bloque que lo encierra.

over 4 years ago · Santiago Trujillo Report

0

Hay una serie de problemas con su código. No tiene un signo = y no está manejando punteros y tipos correctamente.

Se puede hacer como:

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

Observe cómo usa (struct Test) para establecer el tipo del literal compuesto y & para obtener un puntero hacia él. Lo mismo se aplica al puntero flotante.

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!