1 / 23

Lectures 19 & 20

Lectures 19 & 20. What will I learn in this lecture?. Know how to declare pointer variables. Understand the & (address) and *(indirection) operators. Dynamic Memory Allocation Related Chapter: FER Chapter 12.1, 12.2, 19.1,20. Pointers.

benjamin
Télécharger la présentation

Lectures 19 & 20

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Lectures 19 & 20

  2. What will I learn in this lecture? • Know how to declare pointer variables. • Understand the & (address) and *(indirection) operators. • Dynamic Memory Allocation • Related Chapter: FER Chapter 12.1, 12.2, 19.1,20

  3. Pointers Pointer variables are variables that store memory addresses. Pointers variables are useful in passing storage addresses in function calls (call-by-reference) and for applications involving dynamic data structures (e.g., linked lists) Example:int *intPtr; float *floatPtr; declaresintPtrto be a pointer variable to an object of type integer. andfloatPtrto be a pointer variable to an object of type float.

  4. Pointer Declaration - Syntax We can write the pointer variable declaration asint* intPtr; or asint * intPtr; Note that when we declare more than two pointer variables in one line each pointer name requires an asterisk: int *ptr1, *ptr2; otherwise we are just declaring a regular variable , not a pointer variable.

  5. & Operator There are two C operators that are necessary when using pointer variables. & - the address operator returns the address of a variable 1000 Example: int x = 3; int * ptrX = &x; x 3 1004 1000 ptrX The declaration of ptrX initializes the variable ptrX = &x; ptrXholds the address ofx.We say ptrX “points” to x. We will apply the & operator only to variables, e.g. &77 or &(x+1) are not valid.

  6. & Operator Example: int x;int * pt;pt = &x; /* another way to assign an address to a pointer variable */ Suppose the address of thevariable xis 9640Then, the effect ofpt = &x;will be: x pt Address 9640 9640

  7. * Operator *- means "a pointer to" and is called an indirection operator or dereferencing operator, since a pointer "indirectly" references a value in a storage location. Example: int x;int * pt;pt = &x;To assign the value “3” to the variable x in C: x = 3;We can use the “ * ” operator to indirectly reference x. We can assign “3” to x by: *pt = 3; Here we use the fact that “pt” points to integer values. x pt Address 9640 9640 3

  8. NULL Pointer Assigning aNULLvalue (zero) to a pointer double *ptr; ptr = NULL; /*called a null pointer*/ A null pointer points to nothing. We often depict it as ptr

  9. Example - Call-by-Reference 1. Problem Definition Write a function “swap” that has two input integer arguments. This function should swap the values of the variables. 2. Refine, Generalize, Decompose the problem definition (i.e., identify sub-problems, I/O, etc.) Input = two integers Output= no value is returned to the calling function, but the values of the called variables should be swapped. 3. Develop Algorithm Pass the addresses of the variables and not their values. In the swap function the parameters that hold the addresses are pointers. Use the indirection operator to swap the values.

  10. Example - Good Swap /* C Function to swap values. */#include <stdio.h> void swap(int * , int *); void main(void) /* function header */{int x = 1; int y = 2; swap(&x,&y); /* pass the addresses of x and y */printf("x = %i , y = %i \n",x,y);/* prints x = 2 , y = 1 */ } void swap(int *ptrX , int *ptrY) /* pointer variables */ { int temp = *ptrX; *ptrX = *ptrY ; *ptrY = temp; }

  11. Example - Good Swap Main Memory before call to swap x 1000 1 Address y 1004 2 Main Memory while executing swap, after temp = *ptrX;butbefore *ptrX = *ptrY ; x 1000 1 y 1004 2 Address ptrX 1000 3000 ptrY 1004 3004 temp 1 3008

  12. Example - Good Swap Main Memory while executing swap, after *ptrX = *ptrY ;but before *ptrY = temp; x 1000 2 y 1004 2 Address ptrX 1000 3000 ptrY 1004 3004 temp 1 3008

  13. Example - Good Swap Main Memory while executing swap, after *ptrY = temp;but before return; x 1000 2 y 1004 1 Address ptrX 1000 3000 ptrY 1004 3004 temp 1 3008

  14. Example - DMA example 1. Problem Definition Write a program that reads a list of real numbers into an array from the keyboard (or a file using Unix redirection). The array can be of arbitrary length but the user must first specify the length of the array. The program then calculates the average value, and then prints a list of differences. The differences are computed by taking the original values in the list minus the average. 2. Refine, Generalize, Decompose the problem definition (i.e., identify sub-problems, I/O, etc.) Input = Since the length of the array is specified at run-time we must use Dynamic Memory Allocation. This is accomplished in C by the use of the built-in function calloc (or malloc). Use data-type double to hold the values. Output= The average and the list of differences.

  15. #include <stdio.h> #include <stdlib.h> void main(void) { int k,num; double * datValptr; /* pointer used in DMA */ double datAve; double sum = 0.0;/* prompt the user for the number of array elements */ printf("Please enter the number of array elements:"); scanf("%i",&num);/* use calloc to allocate a block of memory */ datValptr = calloc(num,sizeof(double)); /* verify that calloc was successful */ if (datValptr == NULL) { printf("Memory not allocated!\n"); return; } (continued on next slide)

  16. /* read the values and compute the average */ k = 0; for(k=0;k<num;++k) { scanf("%lf", &datValptr[k]);/* use pointer as array name */sum += datValptr[k]; } /* compute the average */ datAve = sum /num; printf("The average is:%f \n", datAve);/* compute and print the diff list */ for(k=0;k<num;++k) { printf("%f\n", datValptr[k]-datAve); } /* end of for*/ /* free up any memory that was dynamically allocated */ free(datValptr); } /* end of main */

  17. Execution dclsn75> ./a.out Please enter the number of array elements:5 1 2 3 4 5 The average is:3.000000 -2.000000 -1.000000 0.000000 1.000000 2.000000 dclsn75>

  18. Array Names are Constant Pointers The array name in C is assigned the address of the first element of the array. The following code will assign the address ofx[0]to xPtr : float x[50]; float * xPtr; xPtr = x; The assignment statement above is equivalent to: xPtr = &x[0];

  19. calloc and malloc • In C, we can dynamically allocate storage with either of the following two functions (both are in <stdlib.h>). • malloc(numberOfBytes) • calloc(numberOfItems, itemSize) • Both functions return a pointer to the address of the block of storage that has been allocated. If no memory is available, a NULL value will be returned. • Function calloc returns a contiguous block of locations that are initialized to 0 and that can be referenced as array locations, using pointer operations.

  20. free Example: Declare ptr as a pointer variable to data-type double and use dynamic memory allocation (calloc or malloc) to allocate 100 elements of data-type double. double * ptr;ptr = calloc(100,sizeof(double)); or ptr = malloc(100*sizeof(double)); In both cases above (calloc or malloc) return memory locations to the system ("memory manager") with: free (ptr);

  21. String Literal is pointer to an Array A string literal (e.g. “A – your course grade\n”) is actually represented in C by a pointer to an address in memory that holds the first byte of the array of characters. Therefore the following declaration of the pointer variable “string” is valid: char * string = "A – your course grade\n"; and to print the value of “string” , use the “%s” conversion specifier, printf("%s",string); Although a pointer can be used as an array name, we cannot modify the values of “string” by using the square brackets of array notation. string[0] = ‘B’; /* error !!! */ The error is due to the fact that the literal “A – your course grade\n” is stored in a location in memory that cannot be accessed by pointers.

  22. String Literal is pointer to an Array One use of char * pointers is ragged arrays. In lecture 15-36 we used the following code fragment to declare and initialize the array “morse” as : typedef char string[5]; string morse[26] = {".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..","--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--.." }; An alternative would be the use of a ragged “morse” array declared as: typedef char * string; string morse[26] = {".-", "-...", "-.-.", "-..", ".", "..-.", "--.", "....", "..", ".---", "-.-", ".-..","--", "-.", "---", ".--.", "--.-", ".-.", "...", "-", "..-", "...-", ".--", "-..-", "-.--", "--.." };

  23. Ragged arrays The later declaration of the array “morse” is called ragged since each element of the array , morse[0], morse[1], … takes up exactly the number of bytes necessary in memory to hold the initialized strings whereas in the previous declaration of “morse” each element of the array takes exactly five character values in memory no matter what length of the initializing string. As discussed on slide 15, we cannot change the values of the ragged “morse” array. But in the “Morse Code” problem we know that the morse strings should never be changed.

More Related