Estructuras
Ciencias de la Computación III
Diego José Figueroa
¿Qué es un puntero?
¿Cómo se reserva espacio para un puntero?
¿Cómo se libera el espacio de un puntero?
Estructuras
- Colección de variables:
- Potencialmente de diferente tipo.
- Agrupado bajo un mismo nombre.
- Operando como una unidad.
- NO es un objeto.
- Facilitan el manejo de datos complejos.
- Es una definición de un tipo.
Estructuras
struct Point{int x;int y;};struct p = {0, 0};printf("x: %d, y: %d", p.x, p.y);
Estructuras
struct Point{int x;int y;} p = {0, 0};printf("x: %d, y: %d", p.x, p.y);
Estructuras
struct Point newPoint(int x, int y){struct Point p;p.x = x;p.y = y;return p;}
Estructuras
int pointCmp(struct Point a, struct Point b){return a.x == b.x && a.y == a.y;}
¿Comentarios?
Estructuras
int pointCmp(struct Point* a,struct Point* b){return (*a).x == (*b).x && (*b).y == (*b).y;}
¿Y ahora?
Estructuras
int pointCmp(struct Point* a,struct Point* b){return a->x == b->x && a->y == b->y;}
Estructuras
- Al pasar una estructura como argumento se crea una copia completa.
- Esto es ineficiente.
- Es mejor utilizar punteros.
Estructuras
struct Point{int x;int y;};struct Point p = {0, 0};
¿Cuánto espacio en memoria ocupa p?
Estructuras
struct Point{char x;int y;};struct Point p = {0, 0};
¿Cuánto espacio en memoria ocupa p?
Estructuras
- La memoria debe estar alineada
- En múltiplos de 4 bytes (word align)
- sizeof
- Obtiene el tamaño en bytes de un objeto
sizeof struct Point -> 8 bytesEstructuras
struct Node{int index;struct Node next;};
No soportado!
Estructuras
struct Node{int index;struct Node* next;};
Esto sí es válido
Bit fields
- Para nosotros, llamados 'campos'.
- Permiten almacenar varios objetos en un solo word.
- Conjunto de bits adyacentes en un word.
- Muy útil para almacenar 'flags'.
unsigned int is_keyword : 1;Bit fields
struct { unsigned int is_keyword : 1; unsigned int is_extern : 1; unsigned int is_static : 1;}flags;...if(flags.is_static){...}
Union
- Parecido a una estructura.
- Pero sólo puede tomar el valor de uno de los objetos que lo componen
union tag{int iVal;float fVal;double dVal;} t;
t puede ser un int, un float o un double.
Typedef
- Permite darle crear nuevos nombres para tipos de datos.
typedef char* String;String s = "doh!";
Typedef
- Múy útil en combinación con structs;
struct Node{char* value;struct Node* next;}
Typedef
typedef char* String;typedef struct Node* List;struct Node{String value; List next; };
03 - Structures
By Diego Figueroa
03 - Structures
- 845