CSc 352: Lecture-12

Structures, Unions, typedef

Note: All the programs mentioned in this lecture are in:

/home/cs352/SUMMER02/lecture12progs/


A few notes on arrays, pointers etc.

- How to add more space to a pointer???
        - Use realloc:
          void *realloc(void *p, size_t size)
          changes the size of object pointed to by p.
          old values you had will be kept.
          returns a pointer to the new space.



- see allocation.c (related to arrays vs pointers in functions)


STRUCTURES, UNIONS ETC.

- typedef
	- A type can be explicitly associated with an identifier.
	Ex: 
	  typedef char *string;
	  typedef double vector[10];


	- Later in the program these names can be used just as types.


	- Used to give meaningful names, and abbreviate long types.
	see typedef.c  




- STRUCTURES
	- to aggregate variables of diff. types.

	Ex:
	  struct student{
		char *name;
		int id;
		double grade;
	  }


	- members of the structure are name, id, and grade.


	- it's a derived data type.(struct student, is the name)


	- the declaration creates the type but no storage allocted.


	- now this userdefined type can be used for declarations.

	Ex:
	  struct student s1, s2, s3;


	- the declaration now allocates space for s1, s2, and s3.


	- we could also write it as:

	  struct student{
		char *name;
		int id;
		double grade;
	  }s1, s2, s3;
	  which both does the definition of type "struct student"
	  and declaration of s1, s2, s3.


	- to access the members, use "." operator:
	  s1.id=3456;
	  s1.grade=100.0;


	- we can make assignment bw structures of the same type:
	  s1=s2;
	  each member of s1 is assigned to the corr. member of s2.


	- When using structure types, usually typedef used:
	  typedef struct{
		char *student;
		int id;
		double grade;
		} stype;

	  so that each time we declare instead of writing:
	  struct student si, sj;
	  we just write:
	  stype si, sj;
	

	- Since it's a common opertion, accessing the members of
	a struct via pointer, has a special operator "->"

	Ex:
	If we declare  
	stype *s1;
	i.e. s1 is a pointer to the struct, then
	(*s1).id    is the same as s1->id

	see class.c


	- Initialization: similar to arrays

	Ex:
	struct sttype{
		char *name;
		int id;
		double grade;
		}student1 = {"cesim", 1234, 80.0};

	NOTE: Structures are passed by value also, i.e., a local 
	copy of it is made and passed to the function. If it
	contains an array then the array gets copied also. If the
	array member is large then this might be inefficient. 
	Alternative is to pass a pointer to the structure, and access
	it through the pointer.
	
	see stfun.c