Asignación de memoria para una Estructura en C


Tengo la tarea de crear un programa que asigne dinámicamente memoria para una estructura. normalmente usaríamos

x=malloc(sizeof(int)*y);

Sin embargo, ¿qué uso para una variable de estructura? No creo que sea posible hacer

struct st x = malloc(sizeof(struct)); 

, Podría alguien ayudarme? ¡Gracias!

Author: Blackbinary, 2010-02-01

7 answers

Mi favorito:

#include <stdlib.h>

struct st *x = malloc(sizeof *x); 

Tenga en cuenta que:

  • x debe ser un puntero
  • no se requiere fundición
  • incluya el encabezado apropiado
 62
Author: dirkgently,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-02-01 14:40:30

No lo estás haciendo bien. struct st x es una estructura, no un puntero. Está bien si quieres asignar uno en la pila. Para asignar en el montón, struct st * x = malloc(sizeof(struct st));.

 4
Author: David Thornley,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-02-01 14:40:34

struct st* x = malloc( sizeof( struct st ));

 4
Author: Nikolai Fetissov,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-02-01 14:40:36

Esto debería hacer:

struct st *x = malloc(sizeof *x); 
 2
Author: codaddict,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-02-02 12:47:30

struct st *x = (struct st *)malloc(sizeof(struct st));

 1
Author: alemjerus,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-02-01 14:41:28

Es exactamente posible hacer eso - y es la manera correcta

Suponiendo que quisieras escribir

struct st *x = malloc(sizeof(struct st)); 

Ps. Tienes que hacer sizeof (struct) incluso cuando conoces el tamaño de todos los contenidos porque el compilador puede rellenar la estructura para que los memebers estén alineados.

struct tm {
  int x;
  char y;
}

Podría tener un tamaño diferente a

struct tm {
  char y;
  int x;
}
 1
Author: Martin Beckett,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-02-01 14:46:18

Creo que, cuando llamas a sizeof en un tipo struct, C llama recursivamente a sizeof en los campos de struct. Por lo tanto, struct st *x = malloc(sizeof(struct st)); solo funciona realmente si struct st tiene un tamaño fijo. Esto solo es significativo si tiene algo como una cadena de tamaño variable en su estructura y NO desea darle la longitud máxima cada vez.

En general,

struct st *x = malloc(sizeof(struct st));

Funciona. Ocasionalmente, se encontrará con estructuras de tamaño variable o estructuras ' abstractas '(piense: clase abstracta de Java) y el compilador le dirá que no puede determinar el tamaño de la estructura st. En estos casos, o bien tendrá que calcular el tamaño a mano y llamar a malloc con un número, o encontrará una función que devuelve una versión totalmente implementada y malloc'd de la estructura que desea.

 -1
Author: Ritwik Bose,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-02-01 14:51:57