Pointer & Structure
Pointer & Structure
28‐Jun‐20 ARJ 1
Structure and Pointer
Consider the following declaration…
struct student
{
int sapid;
char name[20];
}s1, *s2;
28‐Jun‐20 ARJ 3
Accessing members
s1.sapid; s1.sapid s1.name
10 raj
s1.name; 1001 1005
ptr
ptrsapid; 1001
ptrname; 5000
C:\TurboC++\Disk\TurboC3\BIN\PTR14.C
How one can access members using s2?
28‐Jun‐20 ARJ 4
Dynamic Memory Allocation
A memory from heap is allocated.
Two standard library functions…
malloc();
calloc();
Memory is allocated on fly i.e. at run time….
28‐Jun‐20 ARJ 5
Syntax
malloc() calloc()
• Takes one argument. • Takes two arguments.
• (datatype *) malloc(sizeof(datatype)); • (datatype *) calloc(no-of-elements,
sizeof(datatype));
• Does not initialize the allocated • Initializes all allocated space bits with
memory. zero.
• Eg. (int *) malloc(sizeof(int)); • Eg. (char*)calloc(10, sizeof(char));
28‐Jun‐20 ARJ 6
Program 15
C:\TurboC++\Disk\TurboC3\BIN\ptr15.cpp
28‐Jun‐20 ARJ 7