KEMBAR78
1. C Basics for Data Structures Bridge Course | PPTX
C Basics for Data Structures
Bridge Course
(27.07.2020 – 31.07.2020)
Dr. P. Subathra
Professor
Dept. of Information Technology
KAMARAJ College of Engineering and Technology
Madurai
Tamil Nadu
India
subathrakishore@yahoo.com
8/14/2020
Topics
• Arrays
• Pointers
• Structures
8/14/2020
Functions
Arrays
1. What is an Array?
2. How is it stored in the Memory?
3. Why isn’t there any boundary for an Array?
4. How is a program allocated memory in a system
during compilation and execution?
5. What is a Pointer?
6. What actually is an Array variable?
7. How is Static Memory allocation done for an
Array in C?
8. How is Dynamic Memory allocation done for an
Array in C?
8/14/2020
Arrays - Pointers
1. What is an Array?
2. How is it stored in the Memory?
3. Why isn’t there any boundary for an Array?
4. How is a program allocated memory in a system
during compilation and execution?
5. What is a Pointer?
6. What is a Pointer to a Pointer?
7. What actually is an Array variable?
8. How is Static Memory allocation done for an
Array in C?
9. How is Dynamic Memory allocation done for an
Array in C?
8/14/2020
Introduction
• Arrays
– Structures of related data items
– Static entity - same size throughout program
• A few types
– C-like, pointer-based arrays
– C++, arrays as objects
Arrays
c[6]
-45
6
0
72
1543
-89
0
62
-3
1
6453
78
Name of array (Note that all
elements of this array have
the same name, c)
c[0]
c[1]
c[2]
c[3]
c[11]
c[10]
c[9]
c[8]
c[7]
c[5]
c[4]
Position number of the element
within array c
Declaring Arrays
• Declaring arrays - specify:
– Name
– Type of array
– Number of elements
– Examples
int c[ 10 ];
float hi[ 3284 ];
• Declaring multiple arrays of same type
– Similar format as other variables
– Example
int b[ 100 ], x[ 27 ];
Examples Using Arrays
• Initializers
int n[ 5 ] = { 1, 2, 3, 4, 5 };
– If not enough initializers, rightmost elements become 0
– If too many initializers, a syntax error is generated
int n[ 5 ] = { 0 }
– Sets all the elements to 0
• If size omitted, the initializers determine it
int n[] = { 1, 2, 3, 4, 5 };
– 5 initializers, therefore n is a 5 element array
9
Problem with Arrays
• Sometimes
– Amount of data cannot be predicted beforehand
– Number of data items keeps changing during program
execution
• One solution: find the maximum possible value of N and allocate
an array of N elements
– Wasteful of memory space, as N may be much smaller in some
executions
– Example: maximum value of N may be 10,000, but a particular
run may need to search only among 100 elements
• Using array of size 10,000 always wastes memory in most
cases
10
Better Solution
• Dynamic memory allocation
– Know how much memory is needed after the program is
run
• Example: ask the user to enter from keyboard
– Dynamically allocate only the amount of memory needed
• C provides functions to dynamically allocate memory
– malloc, calloc, realloc
11
Memory Allocation Functions
• malloc
– Allocates requested number of bytes and returns a
pointer to the first byte of the allocated space
• calloc
– Allocates space for an array of elements, initializes
them to zero and then returns a pointer to the memory.
• free
– Frees previously allocated space.
• realloc
– Modifies the size of previously allocated space.
12
Allocating a Block of Memory
• A block of memory can be allocated using the
function malloc
– Reserves a block of memory of specified size and
returns a pointer of type void
– The return pointer can be type-casted to any
pointer type
• General format:
type *p;
p = (type *) malloc (byte_size);
13
Example
p = (int *) malloc(100 * sizeof(int));
– A memory space equivalent to 100 times the
size of an int bytes is reserved
– The address of the first byte of the allocated
memory is assigned to the pointer p of type int
p
400 bytes of space
14
Contd.
• cptr = (char *) malloc (20);
Allocates 20 bytes of space for the pointer cptr of type
char
• sptr = (struct stud *) malloc(10*sizeof(struct stud));
Allocates space for a structure array of 10 elements. sptr
points to a structure element of type struct stud
Always use sizeof operator to find number of bytes for a data type, as
it can vary from machine to machine
15
Points to Note
• malloc always allocates a block of contiguous bytes
– The allocation can fail if sufficient contiguous
memory space is not available
– If it fails, malloc returns NULL
if ((p = (int *) malloc(100 * sizeof(int))) == NULL)
{
printf (“n Memory cannot be allocated”);
exit();
}
16
Releasing the Allocated Space: free
• An allocated block can be returned to the system for
future use by using the free function
• General syntax:
free (ptr);
where ptr is a pointer to a memory block which has
been previously created using malloc
• Note that no size needs to be mentioned for the
allocated block, the system remembers it for each
pointer returned
Pointer Artihmetic
8/14/2020
8/14/2020
P=(int*) malloc(10);
}
8/14/2020
8/14/2020
8/14/2020
8/14/2020
8/14/2020
8/14/2020
8/14/2020
8/14/2020
8/14/2020
8/14/2020
8/14/2020
8/14/2020
8/14/2020
8/14/2020
8/14/2020
Operations not allowed on Pointers
• Addition of two pointers
• Multiplication of Two pointers
• Multiplying a constant to a pointer
• Division of Pointers
• Division of a Pointer by a Constant
8/14/2020
8/14/2020
8/14/2020
8/14/2020
8/14/2020
8/14/2020
Pointer to 1D Array
8/14/2020
8/14/2020
8/14/2020
8/14/2020
8/14/2020
8/14/2020
8/14/2020
8/14/2020
8/14/2020
Pointers in 2D Arrays
• Dynamic Allocation done at the HEAP
8/14/2020
8/14/2020
8/14/2020
8/14/2020
8/14/2020
8/14/2020
8/14/2020
8/14/2020
8/14/2020
7000
8/14/2020
8/14/2020
8/14/2020
8/14/2020
8/14/2020
8/14/2020
8/14/2020
8/14/2020
8/14/2020
8/14/2020
68
Pointers to Pointers
• Pointers are also variables (storing addresses), so
they have a memory location, so they also have an
address
• Pointer to pointer – stores the address of a pointer
variable
int x = 10, *p, **q;
p = &x;
q = &p;
printf(“%d %d %d”, x, *p, *(*q));
will print 10 10 10 (since *q = p)
69
Allocating Pointer to Pointer
int **p;
p = (int **) malloc(3 * sizeof(int *));
p
p[2]
p[1]
p[0]
int ** int *
int *
int *
2D array
70
#include <stdlib.h>
int main()
{
int **array;
array = (int**) malloc(nrows * sizeof(int *));
for(i = 0; i < nrows; i++)
{
array[i] = (int*)malloc(ncolumns * sizeof(int));
}
{
Arrays in C CS-2301, B-Term 2009 71
Arrays as Function Parameters
• void init(float A[], int arraySize);
void init(float *A, int arraySize);
• Are identical function prototypes!
• Pointer is passed by value
• I.e. caller copies the value of a pointer to
float into the parameter A
• Called function can reference through that
pointer to reach thing pointed to
Arrays in C CS-2301, B-Term 2009 72
Arrays as Function Parameters (continued)
• void init(float A[], int arraySize){
int n;
for(n = 0; n < arraySize; n++)
A[n] = (float)n;
} //init
• Assigns values to the array A in place
– So that caller can see the changes!
Allocating new heap memory
CS 3090: Safety Critical Programming in C 73
void *malloc(size_t size);
• Allocate a block of size bytes,
return a pointer to the block
(NULL if unable to allocate block)
void *calloc(size_t num_elements,
size_t element_size);
• Allocate a block of num_elements * element_size bytes,
initialize every byte to zero,
return pointer to the block
(NULL if unable to allocate block)
Note: void * denotes a generic pointer type
Allocating new heap memory
CS 3090: Safety Critical Programming in C 74
void *realloc(void *ptr, size_t new_size);
 Given a previously allocated block starting at ptr,
 change the block size to new_size,
 return pointer to resized block
 If block size is increased, contents of old block may be copied to a
completely different region
 In this case, the pointer returned will be different from the ptr argument,
and ptr will no longer point to a valid memory region
 If ptr is NULL, realloc is identical to malloc
 Note: may need to cast return value of malloc/calloc/realloc:
char *p = (char *) malloc(BUFFER_SIZE);
Deallocating heap memory
CS 3090: Safety Critical Programming in C 75
void free(void *pointer);
• Given a pointer to previously allocated memory,
– put the region back in the heap of unallocated memory
• Note: easy to forget to free memory when no longer
needed...
– especially if you’re used to a language with “garbage
collection” like Java
– This is the source of the notorious “memory leak” problem
– Difficult to trace – the program will run fine for some time,
until suddenly there is no more memory!
Any Doubts…???!!!
8/14/2020

1. C Basics for Data Structures Bridge Course

  • 1.
    C Basics forData Structures Bridge Course (27.07.2020 – 31.07.2020) Dr. P. Subathra Professor Dept. of Information Technology KAMARAJ College of Engineering and Technology Madurai Tamil Nadu India subathrakishore@yahoo.com 8/14/2020
  • 2.
    Topics • Arrays • Pointers •Structures 8/14/2020 Functions
  • 3.
    Arrays 1. What isan Array? 2. How is it stored in the Memory? 3. Why isn’t there any boundary for an Array? 4. How is a program allocated memory in a system during compilation and execution? 5. What is a Pointer? 6. What actually is an Array variable? 7. How is Static Memory allocation done for an Array in C? 8. How is Dynamic Memory allocation done for an Array in C? 8/14/2020
  • 4.
    Arrays - Pointers 1.What is an Array? 2. How is it stored in the Memory? 3. Why isn’t there any boundary for an Array? 4. How is a program allocated memory in a system during compilation and execution? 5. What is a Pointer? 6. What is a Pointer to a Pointer? 7. What actually is an Array variable? 8. How is Static Memory allocation done for an Array in C? 9. How is Dynamic Memory allocation done for an Array in C? 8/14/2020
  • 5.
    Introduction • Arrays – Structuresof related data items – Static entity - same size throughout program • A few types – C-like, pointer-based arrays – C++, arrays as objects
  • 6.
    Arrays c[6] -45 6 0 72 1543 -89 0 62 -3 1 6453 78 Name of array(Note that all elements of this array have the same name, c) c[0] c[1] c[2] c[3] c[11] c[10] c[9] c[8] c[7] c[5] c[4] Position number of the element within array c
  • 7.
    Declaring Arrays • Declaringarrays - specify: – Name – Type of array – Number of elements – Examples int c[ 10 ]; float hi[ 3284 ]; • Declaring multiple arrays of same type – Similar format as other variables – Example int b[ 100 ], x[ 27 ];
  • 8.
    Examples Using Arrays •Initializers int n[ 5 ] = { 1, 2, 3, 4, 5 }; – If not enough initializers, rightmost elements become 0 – If too many initializers, a syntax error is generated int n[ 5 ] = { 0 } – Sets all the elements to 0 • If size omitted, the initializers determine it int n[] = { 1, 2, 3, 4, 5 }; – 5 initializers, therefore n is a 5 element array
  • 9.
    9 Problem with Arrays •Sometimes – Amount of data cannot be predicted beforehand – Number of data items keeps changing during program execution • One solution: find the maximum possible value of N and allocate an array of N elements – Wasteful of memory space, as N may be much smaller in some executions – Example: maximum value of N may be 10,000, but a particular run may need to search only among 100 elements • Using array of size 10,000 always wastes memory in most cases
  • 10.
    10 Better Solution • Dynamicmemory allocation – Know how much memory is needed after the program is run • Example: ask the user to enter from keyboard – Dynamically allocate only the amount of memory needed • C provides functions to dynamically allocate memory – malloc, calloc, realloc
  • 11.
    11 Memory Allocation Functions •malloc – Allocates requested number of bytes and returns a pointer to the first byte of the allocated space • calloc – Allocates space for an array of elements, initializes them to zero and then returns a pointer to the memory. • free – Frees previously allocated space. • realloc – Modifies the size of previously allocated space.
  • 12.
    12 Allocating a Blockof Memory • A block of memory can be allocated using the function malloc – Reserves a block of memory of specified size and returns a pointer of type void – The return pointer can be type-casted to any pointer type • General format: type *p; p = (type *) malloc (byte_size);
  • 13.
    13 Example p = (int*) malloc(100 * sizeof(int)); – A memory space equivalent to 100 times the size of an int bytes is reserved – The address of the first byte of the allocated memory is assigned to the pointer p of type int p 400 bytes of space
  • 14.
    14 Contd. • cptr =(char *) malloc (20); Allocates 20 bytes of space for the pointer cptr of type char • sptr = (struct stud *) malloc(10*sizeof(struct stud)); Allocates space for a structure array of 10 elements. sptr points to a structure element of type struct stud Always use sizeof operator to find number of bytes for a data type, as it can vary from machine to machine
  • 15.
    15 Points to Note •malloc always allocates a block of contiguous bytes – The allocation can fail if sufficient contiguous memory space is not available – If it fails, malloc returns NULL if ((p = (int *) malloc(100 * sizeof(int))) == NULL) { printf (“n Memory cannot be allocated”); exit(); }
  • 16.
    16 Releasing the AllocatedSpace: free • An allocated block can be returned to the system for future use by using the free function • General syntax: free (ptr); where ptr is a pointer to a memory block which has been previously created using malloc • Note that no size needs to be mentioned for the allocated block, the system remembers it for each pointer returned
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
    Operations not allowedon Pointers • Addition of two pointers • Multiplication of Two pointers • Multiplying a constant to a pointer • Division of Pointers • Division of a Pointer by a Constant 8/14/2020
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
    Pointer to 1DArray 8/14/2020
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.
  • 48.
  • 49.
    Pointers in 2DArrays • Dynamic Allocation done at the HEAP 8/14/2020
  • 50.
  • 51.
  • 52.
  • 53.
  • 54.
  • 55.
  • 56.
  • 57.
  • 58.
  • 59.
  • 60.
  • 61.
  • 62.
  • 63.
  • 64.
  • 65.
  • 66.
  • 67.
  • 68.
    68 Pointers to Pointers •Pointers are also variables (storing addresses), so they have a memory location, so they also have an address • Pointer to pointer – stores the address of a pointer variable int x = 10, *p, **q; p = &x; q = &p; printf(“%d %d %d”, x, *p, *(*q)); will print 10 10 10 (since *q = p)
  • 69.
    69 Allocating Pointer toPointer int **p; p = (int **) malloc(3 * sizeof(int *)); p p[2] p[1] p[0] int ** int * int * int *
  • 70.
    2D array 70 #include <stdlib.h> intmain() { int **array; array = (int**) malloc(nrows * sizeof(int *)); for(i = 0; i < nrows; i++) { array[i] = (int*)malloc(ncolumns * sizeof(int)); } {
  • 71.
    Arrays in CCS-2301, B-Term 2009 71 Arrays as Function Parameters • void init(float A[], int arraySize); void init(float *A, int arraySize); • Are identical function prototypes! • Pointer is passed by value • I.e. caller copies the value of a pointer to float into the parameter A • Called function can reference through that pointer to reach thing pointed to
  • 72.
    Arrays in CCS-2301, B-Term 2009 72 Arrays as Function Parameters (continued) • void init(float A[], int arraySize){ int n; for(n = 0; n < arraySize; n++) A[n] = (float)n; } //init • Assigns values to the array A in place – So that caller can see the changes!
  • 73.
    Allocating new heapmemory CS 3090: Safety Critical Programming in C 73 void *malloc(size_t size); • Allocate a block of size bytes, return a pointer to the block (NULL if unable to allocate block) void *calloc(size_t num_elements, size_t element_size); • Allocate a block of num_elements * element_size bytes, initialize every byte to zero, return pointer to the block (NULL if unable to allocate block) Note: void * denotes a generic pointer type
  • 74.
    Allocating new heapmemory CS 3090: Safety Critical Programming in C 74 void *realloc(void *ptr, size_t new_size);  Given a previously allocated block starting at ptr,  change the block size to new_size,  return pointer to resized block  If block size is increased, contents of old block may be copied to a completely different region  In this case, the pointer returned will be different from the ptr argument, and ptr will no longer point to a valid memory region  If ptr is NULL, realloc is identical to malloc  Note: may need to cast return value of malloc/calloc/realloc: char *p = (char *) malloc(BUFFER_SIZE);
  • 75.
    Deallocating heap memory CS3090: Safety Critical Programming in C 75 void free(void *pointer); • Given a pointer to previously allocated memory, – put the region back in the heap of unallocated memory • Note: easy to forget to free memory when no longer needed... – especially if you’re used to a language with “garbage collection” like Java – This is the source of the notorious “memory leak” problem – Difficult to trace – the program will run fine for some time, until suddenly there is no more memory!
  • 76.