int marks[10]; // fixed size and fixed address No change in Memory address.

Similar documents
Dynamic Memory Allocation

Computer Programming Unit 3

Pointers (part 1) What are pointers? EECS We have seen pointers before. scanf( %f, &inches );! 25 September 2017

Jagannath Institute of Management Sciences Lajpat Nagar. BCA II Sem. C Programming

Arrays and Pointers (part 1)

Arrays and Pointers (part 1)

Subject: Fundamental of Computer Programming 2068

Arrays and Pointers. CSE 2031 Fall November 11, 2013

dynamic memory allocation

Dynamic memory allocation

C Pointers. Abdelghani Bellaachia, CSCI 1121 Page: 1

Arrays and Pointers. Arrays. Arrays: Example. Arrays: Definition and Access. Arrays Stored in Memory. Initialization. EECS 2031 Fall 2014.

Memory Management. CSC215 Lecture

PESIT Bangalore South Campus Hosur road, 1km before ElectronicCity, Bengaluru -100 Department of Basic Science and Humanities

Lecture 5: Multidimensional Arrays. Wednesday, 11 February 2009

19-Nov CSCI 2132 Software Development Lecture 29: Linked Lists. Faculty of Computer Science, Dalhousie University Heap (Free Store)

Chapter 14. Dynamic Data Structures. Instructor: Öğr. Gör. Okan Vardarlı. Copyright 2004 Pearson Addison-Wesley. All rights reserved.

Variation of Pointers

Arrays, Pointers and Memory Management

Dynamic memory allocation (malloc)

Computer Programming. C Array is a collection of data belongings to the same data type. data_type array_name[array_size];

MODULE V: POINTERS & PREPROCESSORS

C-Refresher: Session 06 Pointers and Arrays

United States Naval Academy Electrical and Computer Engineering Department EC310-6 Week Midterm Spring AY2017

Content. In this chapter, you will learn:

Programming. Pointers, Multi-dimensional Arrays and Memory Management

A. Year / Module Semester Subject Topic 2016 / V 2 PCD Pointers, Preprocessors, DS

Fundamental of Programming (C)

Unit IV & V Previous Papers 1 mark Answers

Memory Allocation. General Questions

CSE2301. Dynamic memory Allocation. malloc() Dynamic Memory Allocation and Structs

NCS 301 DATA STRUCTURE USING C

MODULE 5: Pointers, Preprocessor Directives and Data Structures

C programming basics T3-1 -

APS105. Malloc and 2D Arrays. Textbook Chapters 6.4, Datatype Size

Memory Allocation in C

MODULE 1. Introduction to Data Structures

ESC101N: Fundamentals of Computing End-sem st semester

INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR Stamp / Signature of the Invigilator

int Return the number of characters in string s.

Procedural Programming

Lecture07: Strings, Variable Scope, Memory Model 4/8/2013

Announcements. assign0 due tonight. Labs start this week. No late submissions. Very helpful for assign1

Quick review pointer basics (KR ch )

F.Y. Diploma : Sem. II [CO/CD/CM/CW/IF] Programming in C

High Performance Programming Programming in C part 1

Scheme of valuations-test 3 PART 1

Procedural programming with C

Dynamic Allocation of Memory Space

i location name 3 value at location 6485 location no.(address)

ECE264 Fall 2013 Exam 3, November 20, 2013

Pointers. Introduction

Language comparison. C has pointers. Java has references. C++ has pointers and references

Memory. What is memory? How is memory organized? Storage for variables, data, code etc. Text (Code) Data (Constants) BSS (Global and static variables)

#include <stdio.h> int main() { char s[] = Hsjodi, *p; for (p = s + 5; p >= s; p--) --*p; puts(s); return 0;

It is necessary to have a single function main in every C program, along with other functions used/defined by the programmer.

Lecture 8 Dynamic Memory Allocation

ch = argv[i][++j]; /* why does ++j but j++ does not? */

Programming Language B

CS 11 C track: lecture 5

Dynamic Data Structures. CSCI 112: Programming in C

C PROGRAMMING Lecture 5. 1st semester

Pointers, Arrays, and Strings. CS449 Spring 2016

A3-R3: PROGRAMMING AND PROBLEM SOLVING THROUGH 'C' LANGUAGE

Arrays. An array is a collection of several elements of the same type. An array variable is declared as array name[size]

advanced data types (2) typedef. today advanced data types (3) enum. mon 23 sep 2002 defining your own types using typedef

PDS Class Test 2. Room Sections No of students

These problems are provided to you as a guide for practice. The questions cover important concepts covered in class.

C: Pointers. C: Pointers. Department of Computer Science College of Engineering Boise State University. September 11, /21

Understanding Pointers

Procedural Programming & Fundamentals of Programming

This code has a bug that allows a hacker to take control of its execution and run evilfunc().

Linked-List Basic Examples. A linked-list is Linear collection of self-referential class objects, called nodes Connected by pointer links

Introduction to C. Systems Programming Concepts

Kurt Schmidt. October 30, 2018

UNIT 6. STRUCTURED DATA TYPES PART 1: ARRAYS

Computers Programming Course 12. Iulian Năstac

C Tutorial Pointers, Dynamic Memory allocation, Makefile

Solution for Data Structure

From Java to C. Thanks to Randal E. Bryant and David R. O'Hallaron (Carnegie-Mellon University) for providing the basis for these slides

This document can be downloaded from with most recent updates. 1 Data Structures using C: Module 4 (16MCA11) LINKED LISTS

C Tutorial. Pointers, Dynamic Memory allocation, Valgrind, Makefile - Abhishek Yeluri and Yashwant Reddy Virupaksha

Lecture 07 Debugging Programs with GDB

CS 61C: Great Ideas in Computer Architecture. C Arrays, Strings, More Pointers

POINTERS. Content. Pointers. Benefits of Pointers. In this chapter, you will learn:

Q 1. Attempt any TEN of the following:

Pointers and File Handling

AMCAT Automata Coding Sample Questions And Answers

Chapter 11: Pointers

Linked List in Data Structure. By Prof. B J Gorad, BECSE, M.Tech CST, PHD(CSE)* Assistant Professor, CSE, SITCOE, Ichalkaranji,Kolhapur, Maharashtra

POINTER AND ARRAY SUNU WIBIRAMA

Programming & Data Structure Laboratory. Arrays, pointers and recursion Day 5, August 5, 2014

B.V. Patel Institute of Business Management, Computer & Information Technology, Uka Tarsadia University

MODULE Z THE C STORAGE CLASSES, SCOPE AND MEMORY ALLOCATION

Arrays Arrays and pointers Loops and performance Array comparison Strings. John Edgar 2

Structures, Unions, and Enumerations

DECISION CONTROL AND LOOPING STATEMENTS

Fundamentals of Programming. Lecture 14 Hamed Rasifard

20 Dynamic allocation of memory: malloc and calloc

Technical Questions. Q 1) What are the key features in C programming language?

Transcription:

Dynamic Memory Allocation : Used When we want to allocate memory during run time. int marks[10]; // fixed size and fixed address No change in Memory address. // fixed size. ( no change in size possible We have to use <stdlib.h> hadder file for dynamic memory allocation. It has 4 functions. 1. malloc() 2. calloc() 3. free() 4. realloc() malloc() memory allocation allocate the one memory block given by user. // eg. Reserves 20bytes of block calloc() creates number of blocks. // uses for arrays free() used to free the space after using malloc() or alloc() realloc() if used malloc() or alloc() and need to modified memory block size realloc() ********* ************ ************ ***********************

malloc() creates the memory block according to given size (). malloc() function Also returns the address, which points the address of the first byte in that specific block. Syntax : void * maclloc(size in byte ); as it has void pointer as return type it can return Any type of data : int, string, char. ptr = (cast_type*) malloc( size in byte); ptr = (int*)malloc(10); you must cast the pointer according to type of data eg. Here.. (int *) here, ptr will be int type. int 2 byte it contains garbage value. And here it can hold 5 int values if one int requires 2 bytes in case because of the some problem if memory is not allocated by malloc() function than It will return null pointer.

#include<stdio.h> #include<conio.h> #include<stdlib.h> main() int n, *ptr, sum =0, i, *p; printf( Enter the size of array ); scanf( %d,&n); ptr = (int*)malloc(n* sizeof(int)); // ptr will point the first byte of the memory block. // now we can use null pointer to see block is created or not. if( ptr == NULL) printf( Error : out of Memory ); exit(0); p = ptr; // right now both have the same address. printf( Enter the elements in Array ); for( i= 1; i<=n; i++) scanf( %d,ptr); sum = sum + *ptr; ptr++; printf( Array Elements : ); for(i=1; i<=n; i++) Printf( %d,*p); p++; printf( addition is %d, sum);

calloc() malloc ()creates only one block.. while calloc() can create multiple blocks. calloc() can be used for arrays. void *calloc( number_of_blocks, size for each block in bytes); Syntax : pointer = (Data_Type*) calloc(n,size in bytes); // here function calloc() returns the address of first byte of first block. // malloc() has garbage value in all variables while calloc initionalize with 0. // returns null pointer if block is not created successfully.

Example Programm for calloc() in C #include<stdio.h> #include<stdlib.h> // malloc(), calloc() and other functions are here in this file. main() int n, *ptr, *p, i, sum=0; printf( number of elements to be entered ); scanf( %d,&n); ptr = (int *)calloc(n, sizeof(int)); p= ptr; if(ptr == NULL) printf( memory block is not created successfully); exit(0); // 0 means normal termination. printf( enter %d elements,n); for(i =1; i<=n; i++) scanf( %d,ptr); sum = sum + *ptr; ptr++; printf( Elements are ); for(i =1; i<=n; i++) printf( %d, *p); p++; printf( Addition = %d,sum); free(ptr); // free can be used to free the memory so that we can use that memory in other program. // calloc has 2 arguments and can create more than 1 block.

Realloc() realloc() function is used to change the size of the memory which is allocated by malloc() or alloc(). You can increase / decrease the size of memory using realloc(). It returns void pointer. Syntax : void * realloc(void *ptr, NewSizeInBytes); Here ptr: is old pointer by which the memory allocation is done using malloc or calloc function. Pointer = (cast_type*) realloc( ptr, New_Size_in_bytes); =====*****************=================************* Write a program that stores names of the best hospitals in Riyadh into an array of strings. o Define a constant variable MAX and make it equal to 5. o Use the main code provided in the end of this question. Which shows a menu where the user will choose one of the 4 options: Add a new hospital name: Which calls AddName function. Delete a hospital name: Which calls RemoveName function. Print the hospitals names: Which calls PrintNames function. Exit: Which terminates the program. Write the following functions:

o Write the function AddName that takes an array of strings pointers called Names and a pointer of integer size. Check if there is still enough space to store a new name. Hint: you will need to use the value of MAX to check. If there is a space, ask the user to input the hospital name and store it in a huge array of char (70 char). Calculate the length of the hospital name. Allocate a dynamic memory to store the entered hospital name and store its location in one of Names indexes. Increment the size by one. void AddName(char *Names[],int *size) o Write the function RemoveName that takes an array of strings pointers called Names and a pointer of integer size. Check if the array is not empty. If it s not, asks the user to input the index of the hospital name that he wants to delete. Assume that the user will enter indices starting from 0. If the entered index is within a correct range of indices, Free the dynamically allocated memory. Shift left all the hospitals names that comes after it. Decrement the size by one. void RemoveName(char *Names[],int *size) o Write the function PrintNames that takes an array of strings pointers called Names and an integer size. Then prints all of the names separated by commas (,). Hint: Make sure that the array is not empty before printing. void PrintNames(char *Names[],int size) Model Answer: #include <stdio.h> #include <string.h> #include <stdlib.h> #define MAX 5 void AddName(char *[],int *); void RemoveName(char *[],int *); void PrintNames(char *[],int); int main() char *Names[MAX]; int size = 0; int c;

do printf("=========================\n"); printf("1- Add a new name.\n"); printf("2- Delete an old name.\n"); printf("3- Print names.\n"); printf("4- Exit.\n"); printf("=========================\n"); printf("enter your choice: "); scanf("%i", &c); printf("=========================\n"); switch(c) case 1: AddName(Names,&size); break; case 2: RemoveName(Names,&size); break; case 3: PrintNames(Names,size); break; case 4: printf("good bye.\n"); break; default: printf("error: Bad input.\n");

while(c!= 4); void AddName(char *Names[],int *size) int Copysize = *size; char *s; if (Copysize >= MAX) printf("\n ERROR: Array is full. Cannot add."); else int i,length=0; char name[100]; printf("enter the name: "); scanf("%s",name); for(i=0; name[i]!='\0'; i++) length++; s = (char *)malloc((length+1)*sizeof(char)); strcpy(s, name); Names[*size]=s; *size=*size+1; printf("\n The entered data has been added successfully.\n");

void RemoveName(char *Names[],int *size) if (*size == 0) printf("there are no data to delete"); else int index, i; printf("please Enter the index of the element you want to delete starting from 0 "); scanf("%d", &index); if(index<0 index >= MAX) printf("the entered index is incorrect"); return;

if(index >= *size) printf("the entered index is already free, There is nothing to be deleted"); return; free(names[index]); for (i=index; i<max-1; i++) Names[i] = Names[i+1]; [MAX-1] = NULL; *size= *size-1; printf("deletion is done successfully"); void PrintNames(char *Names[],int size) int i; if (size>0) for(i=0; i<size; i++) printf("%s, ",*(Names+i));("\n"); else printf("there are No data to print"); printf("\n");