pointers & dynamic memory allocations in c

31
Pointers & Dynamic Memory Allocations in C CHAPTER 3

Upload: barto

Post on 11-Jan-2016

47 views

Category:

Documents


1 download

DESCRIPTION

Pointers & Dynamic Memory Allocations in C. CHAPTER 3. Pointers verses Variables. Pointers are variables that contains memory addresses. A variable contains a specific value. A pointer contains the address of a variable that contains a specific value. - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Pointers  & Dynamic Memory Allocations   in C

Pointers & Dynamic MemoryAllocations in C

CHAPTER 3

Page 2: Pointers  & Dynamic Memory Allocations   in C

C.032

Pointers verses Variables

» Pointers are variables that contains memory addresses.

» A variable contains a specific value.

» A pointer contains the address of a variable that contains a specific value.

» Like other variables, pointer must be declared before they can be used.

Page 3: Pointers  & Dynamic Memory Allocations   in C

C.033

Pointer Declaration» Just like variables, each pointer has a name and a data type that can be at the pointed address.e.g.:

int *ptr ; // A pointer declarationint cnt=32 ; // A variable declaration

… ptr = &cnt ;

» Note that, pointer names have an indicator ( * ) character, that is differentiating them from variable names.

» At the previous example, ptr is declared as a pointer, which pointing a memory address contains an integer value.

Page 4: Pointers  & Dynamic Memory Allocations   in C

C.034

Pointer Declaration

» Pointers are indirectly referencing variables.

cnt

32

32

ptr

cnt

ptr is indirectly references a variablewhose value is 32.

cnt is directly references a variablewhose value is 32.

Page 5: Pointers  & Dynamic Memory Allocations   in C

C.035

Operators Used with Pointers

» & : The “address of ” operator is used mostly just before any variable name for indicating its memory address.

» * : The content of operator is used before a variable name, for indicating the specific value existing at the address pointer contains.

» Note that, & operator is used with variables, and * operator is used with pointers.

Page 6: Pointers  & Dynamic Memory Allocations   in C

C.036

Operators Used with Pointers

e.g.:int x=1, y=2;int *ip;ip = &x; // The address of x is assigned to ipy = *ip; // The content of the address ip has

// is copied to the variable y. (y=x)printf(“x=%d y=%d”, x, y);

The output will be: x=1 y=1

Page 7: Pointers  & Dynamic Memory Allocations   in C

C.037

Operators Used with Pointers

e.g.:int x=1;int *ip;ip = &x;*ip = *ip + 10;

/* The value 10 is added to the content of the address ip has */

printf(“x=%d *ip=%d”, x, *ip);

The output will be: x=11 *ip=11

Page 8: Pointers  & Dynamic Memory Allocations   in C

C.038

Operators Used with Pointers

e.g.:*ip +=1; is same as ++ *ip; and *ip ++;

»All of them above increments the value of the address in ip by 1.

e.g.:*(ip++); is indicating the value of the NEXT

address, which ip has.

*(ip++) *ip++

Page 9: Pointers  & Dynamic Memory Allocations   in C

C.039

Operators Used with Pointers e.g.:

#include <stdio.h>void main(){ int u=3, v, *pu, *pv;pu = &u;v = *pu;pv = &v;printf(“\n u=%d, *pu = %d”, u, *pu);

printf(“\n v=%d, *pv = %d”, v, *pv);}

The output will be:u=3, *pu=3v=3, *pv=3

Page 10: Pointers  & Dynamic Memory Allocations   in C

C.0310

Operators Used with Pointers e.g.:

#include <stdio.h>void main(){ int u1, u2, v=3, *pv;u1 = 2 * ( v + 5);pv = &v;u2 = 2 * ( *pv + 5);printf(“\n u1 = %d, u2 = %d”, u1, u2);}

The output will be:u1= 16, u2 = 16

Page 11: Pointers  & Dynamic Memory Allocations   in C

C.0311

Operators Used with Pointers e.g.:

#include <stdio.h>void main(){ int u=1, v=2, *pv;

printf(“\n u = %d, v = %d”, u, v);pv = &u;*pv = 6;

printf(“\n u = %d, v = %d”, u, v);pv = &v;*pv = 0;

printf(“\n u = %d, v = %d”, u, v);}

The output will be:u= 1, v = 2u= 6, v = 2u= 6, v = 0

Page 12: Pointers  & Dynamic Memory Allocations   in C

C.0312

Pointers and Arrays» When an array is declared, the followings are done automatically:

»The array size of spaces are allocated within the memory.

»A pointer as the array name is declared.

» The address of the first location is assigned to the pointer( so, it points the initial array element).

» So, the followings are exactly same:myarray = &myarray[0]myarray+1 = &myarray[1]myarray + 9 = &myarray[9]

Page 13: Pointers  & Dynamic Memory Allocations   in C

C.0313

Pointers and Arrays e.g.:

int list[5]=“1, 3, 5, 7, 9}, *pv;pv = list;

*(pv+3) = 12;

11 22 33 44 55List

pv

11 22 33 1212 55List

pv

Page 14: Pointers  & Dynamic Memory Allocations   in C

C.0314

Pointers and Arrayse.g.:

#include <stdio.h>void main(){ int i, list[5]={5,10,15,20,25}, *pv; pv=list; for (i=0; i< 5; i++) *(pv + i)= *(pv+i) + 2; for (i=0; i< 5; i++) printf(“%d ,”,list[i]);}

Output will be:

7, 12, 17, 22, 27

Page 15: Pointers  & Dynamic Memory Allocations   in C

C.0315

Pointers and Arrayse.g.:

#include <stdio.h>void main(){ int i =0; char line[81], *pv; gets(line); while (*(line+i) !=‘\0’) { printf(“%c”,*(line+i)); i++;}} // End of program

» This program reads a line at most 80 character and then displays it character by character.

Page 16: Pointers  & Dynamic Memory Allocations   in C

C.0316

Pointers and Arrayse.g.: Read elements of an array and find the sum of array elements with using pointers. #include <stdio.h> void main() { int i =0, arr[5], *parr, sum = 0;

for(i=0; i<5; i++) { printf(“\n Enter the value of location %d”,i+1); scanf(“%d”, &arr[i]); }parr = arr; for(i=0; i<5; i++) { sum += *(parr+i) }printf(“\n The sum is found %d”,sum);

} // End of program

Page 17: Pointers  & Dynamic Memory Allocations   in C

C.0317

Pointers and Function Arguments» When a variable is used as an argument on a function call, the value of this variable is being passed into the function

» if variable is not globally declared, its content can not be altered in the function).

»When a pointer is used as an argument on a function call, the address in the pointer is being passed into the function.

» So, just like globally declared variables, in the function, the content of a local variable, that its address is passed into the function, can be altered.

Page 18: Pointers  & Dynamic Memory Allocations   in C

C.0318

Pointers and Function Arguments#include <stdio.h>void funct1(int, int);void funct2(int *, int *);void main(){ int u = 1, v = 3; printf(“\n Before calling func1, u=%d , v=%d”,u,v); func1(u, v); printf(“\n After calling funct1, u=%d , v=%d”,u,v); funct2(&u, &v); printf(“\n After calling funct2, u=%d , v=%d”,u,v);}

void funct1( int u, int v){ // The Output will be u= 0; v=0; // Before Calling func1 u = 1, v = 3} // After Calling funct1 u = 1, v = 3

// After Calling funct2 u = 0, v= 0void funct2( int *pu, int *pv){ *pu= 0; *pv=0;}

Page 19: Pointers  & Dynamic Memory Allocations   in C

C.0319

Examplese.g.: /* Read a character string and display it in reverse order*/#include <stdio.h>

void main()

{ char line[81], *pline ;

printf(“\n Enter a string of characters :”);

gets(line);

for (pline=line; *pline !=‘\0’, pline++); // Goes to the last character.

pline - -; // Comes back to the last character

for (; pline > line; pline - -) // Display characters from last to 2th

printf(“%c ”, *pline );

pline--; printf(“%c ”,*pline ); // Display the last character

}

Page 20: Pointers  & Dynamic Memory Allocations   in C

C.0320

Examplese.g.: /* Count the number of characters of a string */#include <stdio.h>void main(){ int cnt = 0; char line[81], *pline ; printf(“\n Enter a string of characters :”); gets(line); for (pline = line; *pline ; pline++) {

++cnt; } printf(“\n There are %d characters”,cnt);}

Page 21: Pointers  & Dynamic Memory Allocations   in C

C.0321

Examplese.g.: /* Count the occurrence of a character within a string */#include <stdio.h>void main(){ int cnt = 0; char line[81], ch, *pline ; printf(“\n Enter a string of characters :”); gets(line); printf(“\n Enter the target character :”); scanf(“%c”, &ch); for (pline = line; *pline; pline++)

if (*pline == ch) ++cnt; printf(“\n There are %d occurrence ”,cnt);}

Page 22: Pointers  & Dynamic Memory Allocations   in C

C.0322

Examplese.g.: /* Reads a character string and counts the existing words */#include <stdio.h>

void main()

{ char line[81], *pline ;

int cword =0;

printf(“\n Enter a string of characters :”);

gets(line);

for (pline=line; *pline ==‘ ’, pline++); // Skips blanks.

while (*pline)

{ cword ++;

for ( ; ((pline !=‘\0’) && ( *pline!=‘ ‘); pline++) ; // skips letters

for ( ; ((pline !=‘\0’) && ( *pline==‘ ‘); pline++) ; // skips blanks

}

printf(“There are %d words in the string.”,cword);

}

Page 23: Pointers  & Dynamic Memory Allocations   in C

C.0323

Examplese.g.: /* Read a character string and display one word each line */#include <stdio.h>

void main()

{ char line[81], *pline ;

printf(“\n Enter a string of characters :”);

gets(line);

for (pline=line; *pline ==‘ ’, pline++); // Skips blanks.

while (*pline)

{ printf(“\n”);

for ( ; ((pline !=‘\0’) && ( *pline!=‘ ‘); pline++)

printf(“%c”,*pline) ; // display letters

for ( ; ((pline !=‘\0’) and ( *pline==‘ ‘); pline++) ; // skips blanks

}

}

Page 24: Pointers  & Dynamic Memory Allocations   in C

C.0324

Dynamic Memory Allocation» The process of allocating and de-allocating memory while the program is in execution is called Dynamic Memory Allocation.

» Specially, on a situation which the memory requirement is not possible to be estimated on program design time, the required memory has to be allocated dynamically on run time.

» Also, when the allocated memory is not going to be used, on run time, it may be de-allocated (free).

Page 25: Pointers  & Dynamic Memory Allocations   in C

C.0325

Dynamic Memory Allocation» On memory allocation, a pointer is required to keep the reference address of the allocated memory.

» The memory allocation functions are declared within the library <alloc.h>.

» malloc(); is the function for allocating a number of bytes within the memory. It returns the reference address of the allocated memory part.

» free(); is the function for de-allocating a memory part that was allocated dynamically.

»The reference address of the memory part has to be given as argument to free().

Page 26: Pointers  & Dynamic Memory Allocations   in C

C.0326

Dynamic Memory Allocation» Consider the following code; they are almost same:e.g.:

void main(){ int list[10];

…}

e.g.:void main(){ int *list; … list = (int *) malloc(10 * sizeof(int));

… free(list);}

Page 27: Pointers  & Dynamic Memory Allocations   in C

C.0327

Array of Pointers» It is an array that all its elements are pointers.

» Elements of an array of pointer may points some other arrays, which can be think as a multidimensional array.

» Really, when a multidimensional array is declared:» A pointer is declared with the name that is equal to the name of the multidimensional array. It points the first element of the array of pointers.

» an array of pointer is declared with size of row number of the matrix, and each element points another array with the same data type the multi dimensional array declared.

Page 28: Pointers  & Dynamic Memory Allocations   in C

C.0328

Array of Pointers int list[5][3] ={1,3,5,7,9,11,13,15,17,19,21,23,25,27,29};

list11 33 55

77 99 1111

1313 1515 1717

1919 2121 2323

2525 2727 2929

An array of pointers

A group of array of integers

Page 29: Pointers  & Dynamic Memory Allocations   in C

C.0329

Array of Pointers»Array of pointers are mostly used with strings. e.g.: (Dynamically created array of strings with fixed string length)

#include <stdio.h>#include <alloc.h>void main(){

char *list[10];int i;

/* Declaration of the dynamic array*/for (i=0; i<10; i++) list[i]= (char *) malloc( 21 * sizeof(char));/* filling up the array*/for (i=0; i<10; i++) { printf(“Enter the name %d :”,i+1); scanf(“%s”,list[i]); }/* rewriting names in reverse entry order*/for (i=9; i>=0; i--)

printf(“\n %s”,list[i]);}

Page 30: Pointers  & Dynamic Memory Allocations   in C

C.0330

Array of Pointerse.g.: (Dynamically created array of strings with variable string length)#include <stdio.h>#include <alloc.h>int strlen( char* );void main(){ char *list[10], line[81];

int i, j, len;for (i=0; i<10; i++) { printf(“\n Enter the name %d =”, i+1); gets(line); len = strlen(line);

list[i]= (char *) malloc( len * sizeof(char)); /* copy line to list[i]*/ for (j=0; j<len; j++) *(list[i]+j) = *(line+j); }/* rewriting names in reverse entry order*/for (i=9; i>=0; i--)

printf(“\n %s”,list[i]);}

Page 31: Pointers  & Dynamic Memory Allocations   in C

C.0331

Array of Pointerse.g.: (Dynamically created array of strings with variable string length)

//<< Continues >>

int strlen( char *pstr );{ int slen=0; for ( ; *pstri ; pstr++)

slen++; return (slen+1)}