Structure and Unions & Memory Allocation
Structure and Unions & Memory Allocation
Structure
A data type to store group of daata with various of data type.
Heterogeneous : various element data type.
Structure component called :
~ member
~ field
~ element
~ in other programming language also called record
Syntax :
struct name_structure {
dataType1 name_field1;
dataType2 name_field2;
…
};
Nested Structure
A structure with one of its element is another structure (should be declared in advance).
Structure Initialization
Syntax :
struct
struct_name variable =
{value_1, …, value_m};
Typedef (other name)
Used for short naming and commonly used in structure
Bit Field
A struct with each element assign with certain number of bit.
syntax :
struct
name{
type
field1: numberof_bit;
…...
};
Union Definition
Union is used for memory join. A memory location can be assigned for two or more variable with different
data types. Memory capacity used by union in the largest capacity used by any element of the union.
Enumeration
A data type with predefined number of data.
• Data type enumeration declaration
enum
name_type {
const1, const2,… const_n
}name_var;
• Enumeration variable
enum name_type name_var;
Static Keyword
Can be used as a variable type or return value type of a function.
Static variable :
~ Allocated at program start and de-allocated at the end of a program.
~ Default value = 0
~ Scope of static variable is inside a file where the variable is defined
Syntax :
static
type variable_name;
Register Variable
Defining a variable store in a register (If possible-register is limited, If rejected : automatic variable)
Syntax :
register
data_type
variable_name;
External Variable
In C modules programs are implemented using function.
A module may consist of several function and save in a file.
If function in a particular file wants to access a variable in other file, then use keyword extern.
Void * Data Type
Constant Char *
Comparing char* with const char* using strcpy
ex :
char *strcpy( char
*strDestination, const
char *strSource );
•Description:
~ char * :
should be a pointer (has an address)
~ const char * : can be string or pointer
•Example:
char ss[20]; char str[20] = ”Good Morning”;
strcpy(ss,”Good Morning”);
strcpy(ss, str);
strcpy(”Hello”, ss); //error
Memory Allocation
Memory Allocation : Acquiring some memory space (RAM) managed by the OS to be used by a program.
Memory De-Allocation : Releasing memory space (RAM) back to the OS
Memory Allocation as a data store :
1) Static
- Can be assigned with name -> variable.
- Allocated at compile time.
- Stored at local stack memory.
- Remain unchanged during the program run.
- De-Allocated when the program end.
2) Dynamic
- Can be assigned with name
- Allocated at run-time
- Stored at heap memory
- Can be De-Allocated at any time
Pointer to Functions
The address of a function in the memory.
Syntax :
return_type
(* pointer_name)(parameter);

Comments
Post a Comment