Presentation is loading. Please wait.

Presentation is loading. Please wait.

Pointers.

Similar presentations


Presentation on theme: "Pointers."— Presentation transcript:

1 Pointers

2 Introduction A pointer is a variable that represents the location (rather than the value) of a data item. int *numPtr; float *fp;

3 Pointer initialization
int *ip; int A[10]; float *fp; int count; float speed; : ip = &count; fp = &speed; ip = &A[4];

4 Pointer Arithmetic pointer + number pointer – number
E.g., pointer + k adds k times scalefactor to a pointer char *p; char a; char b; p = &a; p += 1; int *p; int a; int b; scalefactor = sizeof (data type) In each, p now points to b Adds 1*sizeof(int) to the memory address Adds 1*sizeof(char) to the memory address

5 Passing Pointers to a Function
Pointers may be passed to a function as arguments. Allows data items within the calling program to be accessed by the function, altered, and then returned to the calling program in altered form.

6 Pass-by-Reference void set_x_and_y(int *x, int *y) { *x = 1001;
} void f(void) { int a = 1; int b = 2; set_x_and_y( &a,&b); 1 2 a b 1001 1002 x y

7 Pointers and Arrays When an array is declared,
The compiler allocates a base address and sufficient amount of storage . The base address is the location of the first element The compiler also defines the array name as a constant pointer to the first element.

8 Arrays and Pointers int a[5] = { 1, 2, 3, 4, 5 } ; int *p; int i, j;
Engineering H192 Winter 2005 Arrays and Pointers int a[5] = { 1, 2, 3, 4, 5 } ; int *p; int i, j; Let p = A; Then p points to A[0] p + i points to A[i] &A[j] == p+j *(p+j) is the same as A[j] Instructor: This slide summarizes the various ways to obtain the address and data of each element of an array. Students may wish to print a copy of this slide and use it as a reference until they feel comfortable with using pointers and arrays. Narrator: This slide summarizes the various ways to obtain the address and data of each element of an array. You may wish to print a copy of this slide and use it as a reference until you feel comfortable using pointers and arrays. The array name by itself is a pointer to the beginning of the array, which is also the address of the first element. &a[0] is also the same thing. a[0] returns the value stored in the first element of the array, and so on. You can also perform math with these pointers as shown in the last two lines. Lecture 15

9 FIGURE 10-5 Pointer Arithmetic

10 FIGURE 10-6 Pointer Arithmetic and Different Types

11 Pointers and Structures
You may recall that the name of an array stands for the address of its zero-th element. Also true for the names of arrays of structure variables. Consider the declaration: struct stud { int roll; char dept_code[25]; float cgpa; } class[100], *ptr ;

12 will assign the address of class[0] to ptr. (ptr++) :
The assignment ptr = class ; will assign the address of class[0] to ptr. (ptr++) : The value of ptr is actually increased by sizeof(stud). Once ptr points to a structure variable, the members can be accessed as: ptr –> roll ; ptr –> dept_code ; ptr –> cgpa ; The symbol “–>” is called the arrow operator.

13 Example #include <stdio.h> struct complex { float re; float im; }; int main() { struct complex a, b, c; scanf (“%f %f”, &a.re, &a.im); scanf (“%f %f”, &b.re, &b.im); add (&a, &b, &c) ; printf (“\n %f %f”, c,re, c.im); } void add (struct complex *x, struct complex *y, struct complex *t) { t->re = x->re + y->re ; t->im = x->im + y->im ; }

14 struct foo { // a global definition, the struct foo is known
#include <stdio.h> struct foo { // a global definition, the struct foo is known int a, b, c; // in all of these functions }; // function prototypes void inp (struct foo *); void outp (struct foo); int main( ) { struct foo x; // declare x to be a foo inp(&x); // get its input, passing a pointer to foo outp(x); //send x to outp, requires 2 copying actions }

15 void inp(struct foo *x)
{ scanf("%d%d%d", &x->a, &x->b, &x->c); } void outp(struct foo x) printf("%d %d %d\n", x.a, x.b, x.c);

16 Nested structs In order to provide modularity, it is common to use already-defined structs as members of additional structs struct point { int x; int y; } struct rectangle { struct point pt1; struct point pt2; If we have struct rectangle r; Then we can reference r.pt1.x, r.pt1.y, r.pt2.x and r.pt2.y Now consider the following struct rectangle r, *rp; rp = &r; Then the following are all equivalent r.pt1.x rp->pt1.x (r.pt1).x (rp->pt1).x But not rp->pt1->x (since pt1 is not a pointer to a point)

17 Arrays of structs To declare an array of structs (once you have defined the struct): struct rectangle rects[10]; rects now is a group of 10 structures (that consist each of two points) You can initialize the array as normal where each struct is initialized as a { } list as in {5, 3} for a point or {{5, 3}, {8, 2}} for a rectangle

18 Example struct point{ int x int y; }; struct rectangle { struct point p1; struct point p2; void printRect(struct rectangle r) { printf("<%d, %d> to <%d, %d>\n", r.p1.x, r.p1.y, r.p2.x, r.p2.y); } int main( ) int i; struct rectangle rects[ ] = {{{1, 2}, {3, 4}}, {{5, 6}, {7, 8}}}; // 2 rectangles for(i=0;i<2;i++) printRect(rects[i]);

19 Revisited Character Array / String

20 Introduction A string is an array of characters.
Individual characters are stored in memory in ASCII code. A string is represented as a sequence of characters terminated by the null (‘\0’) character. Because C stores a string as an array, the name of the string is a pointer to the beginning of the string. C implements strings logically, not physically. The physical structure of a string is the array in which C stores the string. “Hello”  ‘\0’ l e H o

21 Declaring String Variables
A string is declared like any other array: char string-name [size]; size determines the number of characters in string_name. When a character string is assigned to a character array, it automatically appends the null character (‘\0’) at the end of the string. char city[15]; char dob[11]; A string may be initialized at the time of declaration. char city[15] = “Calcutta”; char city[15] = {‘C’, ‘a’, ‘l’, ‘c’, ‘u’, ‘t’, ‘t’, ‘a’}; char dob[] = “ ”;

22 Reading “words” scanf can be used with the “%s” format specification.
char name[30]; : scanf (“%s”, name); The ampersand (&) is not required before the variable name with “%s”. The problem here is that the string is taken to be upto the first white space (blank, tab, carriage return, etc.) If we type “Amit Ray” name will be assigned the string “Amit”

23 getchar() (or scanf (“%c”, …)
char line[81], ch; int c=0; : do { ch = getchar(); line[c] = ch; c++; } while (ch != ‘\n’); c = c – 1; line[c] = ‘\0’;

24 Reading a line :: Alternate Approach
char line[81]; : scanf (“%[ ABCDEFGHIJKLMNOPQRSTUVWXYZ]”, line); Reads a string containing uppercase characters and blank spaces char line[81]; : scanf (“%[^\n]”, line); Reads a string containing any characters

25 The gets() Function The gets() function (from stdio) takes a string from standard input and assigns it to a character array. It replaces the \n with \0. To use gets(): gets(myString); The gets() function includes no way to check the length of the input string!

26 Writing Strings to the Screen
We can use printf with the “%s” format specification. char name[50]; : printf (“\n %s”, name);

27 Processing Character Strings
There exists a set of C library functions for character string manipulation. strcpy :: string copy strlen :: string length strcmp :: string comparison strtcat :: string concatenation It is required to include the following #include <string.h>

28 Copying strings We cannot simply assign one string to another due to the that strings are character arrays! strcpy () Works very much like a string assignment operator. strcpy (destinationString, sourceString); Examples: strcpy (city, “Calcutta”); strcpy (city, mycity);

29 strlen() Counts and returns the number of characters in a string.
len = strlen (string); /* Returns an integer */ The null character (‘\0’) at the end is not counted. Counting ends at the first null character.

30 char city[15]; int n; : strcpy (city, “Calcutta”); n = strlen (city); n is assigned 8

31 Comparing Strings: strcmp()
Compares two character strings. int strcmp (str1, str2); If the two strings are equal, strcmp() returns 0. If str1 is greater than str2, strcmp() returns a positive number. If str1 is less than str2, strcmp() returns a negative number.

32 Comparing Strings

33 Combining Strings: strcat()
Joins or concatenates two strings together. strcat (string1, string2); string2 is appended to the end of string1. The null character at the end of string1 is removed, and string2 is joined at that point. Example: strcpy (name1, “Amit “); strcpy (name2, “Roy“); strcat (name1, name2); ‘\0’ i m A t ‘\0’ y o R i m A t ‘\0’ y o R

34 /* Read a line of text and count the number of uppercase letters */
#include <stdio.h> #include <string.h> main() { char line[81]; int i, n, count=0; printf(“Input the line \n”); scanf (“%[^\n]”, line); n = strlen (line); for (i=0; i<n; i++) if (isupper (line[i])) count++; } printf (“\n The number of uppercase letters in the string %s is %d”, line, count); Include header for string processing Character Array for String Reading a line of text Computing string length Checking whether a character is Uppercase

35 Two Dimensional Arrays
We have seen that an array variable can store a list of values. Many applications require us to store a table of values. Subject 1 Subject 2 Subject 3 Subject 4 Subject 5 75 82 90 65 76 68 80 70 72 88 74 85 50 40 Student 1 Student 2 Student 3 Student 4

36 Contd. The table contains a total of 20 values, five in each line.
The table can be regarded as a matrix consisting of four rows and five columns. C allows us to define such tables of items by using two-dimensional arrays.

37 Declaring 2-D Arrays General form: Examples:
type array_name [row_size][column_size]; Examples: int marks[4][5]; float sales[12][25]; double matrix[100][100];

38 Accessing Elements of a 2-D Array
Similar to that for 1-D array, but use two indices. First indicates row, second indicates column. Both the indices should be expressions which evaluate to integer values. Examples: x[m][n] = 0; c[i][k] += a[i][j] * b[j][k]; a = sqrt (a[j*3][k]);

39 How is a 2-D array is stored in memory?
Starting from a given memory location, the elements are stored row-wise in consecutive memory locations. x: starting address of the array in memory c: number of columns k: number of bytes allocated per array element a[i][j] is allocated memory location at address x + (i * c + j) * k a[0]0] a[0][1] a[0]2] a[0][3] a[1][0] a[1][1] a[1][2] a[1][3] a[2][0] a[2][1] a[2][2] a[2][3] Row 0 Row 1 Row 2

40 How to read the elements of a 2-D array?
By reading them one element at a time for (i=0; i<nrow; i++) for (j=0; j<ncol; j++) scanf (“%f”, &a[i][j]); The ampersand (&) is necessary. The elements can be entered all in one line or in different lines.

41 How to print the elements of a 2-D array?
By printing them one element at a time. for (i=0; i<nrow; i++) for (j=0; j<ncol; j++) printf (“\n %f”, a[i][j]); The elements are printed one per line. printf (“%f”, a[i][j]); The elements are all printed on the same line.

42 Contd. for (i=0; i<nrow; i++) { printf (“\n”);
for (j=0; j<ncol; j++) printf (“%f ”, a[i][j]); } The elements are printed in matrix form.

43 Example: Matrix Addition
int main() { int a[100][100], b[100][100], c[100][100], p, q, m, n; scanf (“%d %d”, &m, &n); for (p=0; p<m; p++) for (q=0; q<n; q++) scanf (“%d”, &a[p][q]); scanf (“%d”, &b[p][q]); for (p=0; p<m; p++) for (q=0; q<n; q++) c[p]q] = a[p][q] + b[p][q]; { printf (“\n”); printf (“%f ”, a[p][q]); }

44 Passing Arrays to a Function
An array name can be used as parameter of a function, which is effectively the address of the first element. When an array is passed to a function, the values of the array elements are not passed to the function. The array name is interpreted as the address of the first array element. The formal argument therefore becomes a pointer to the first array element. When an array element is accessed inside the function, the address is calculated using the formula stated before. Changes made inside the function are thus also reflected in the calling program.

45 Passing 2-D Arrays Similar to that for 1-D arrays.
The array contents are not copied into the function. Rather, the address of the first element is passed. For calculating the address of an element in a 2-D array, we need: The starting address of the array in memory. Number of bytes per element. Number of columns in the array. The above three pieces of information must be known to the function.

46 Example Usage #include <stdio.h> int main() {
int a[15][25], b[15]25]; : add (a, b, 15, 25); } void add (x, y, rows, cols) int x[][25], y[][25]; int rows, cols; { : } We can also write int x[15][25], y[15][25]; Number of columns

47 Example: Transpose of a matrix
void transpose (int x[][100], int n) { int p, q; for (p=0; p<n; p++) for (q=0; q<n; q++) t = x[p][q]; x[p][q] = x[q][p]; x[q][p] = t; } a[100][100] transpose(a,3)

48 The Correct Version void transpose (int x[][100], n) { 20 30 int p, q;
for (p=0; p<n; p++) for (q=p; q<n; q++) t = x[p][q]; x[p][q] = x[q][p]; x[q][p] = t; }

49 Multi-Dimensional Arrays
How can you add more than two dimensions? int a[100]; int b[100][100]; int c[100][100][100]; ……. How long? Can you add any dimension? Can you add any size?

50 Dynamic Memory Allocation
Dynamic memory is memory that is “requested” at run-time Solves two fundamental dilemmas: How can we control the amount memory used based on run time conditions? How can we control the lifetime of memory?

51 Memory Usage + Heap Variable memory is allocated in three areas:
0x0000 Trap Vector Table Variable memory is allocated in three areas: Global data section Run-time stack Dynamically allocated - heap Global variables are allocated in the global data section and are accessible from all parts of the program. Local variables are allocated during execution on the run-time stack. Dynamically allocated variables are items created during run-time and are allocated on the heap. Interrupt Vector Table Trap Routines Operating System 0x3000 Program Code Global Data Section (Global and Static vars) Heap (Dynamically allocated vars) Run-Time Stack (Local and Auto vars) 0xFFFF I/O Space

52 Memory Allocation Functions
malloc Takes a size_t representing the number of bytes requested Returns a void* pointing to the start of the block or NULL if there was an error The return pointer can be assigned to any pointer type. General format: ptr = (type *) malloc (byte_size) ; The allocation can fail if sufficient contiguous memory space is not available. If it fails, malloc returns NULL.

53 malloc int *ip; If ((ip = (int *) malloc(10*sizeof(int))) == NULL) {
/* Handle Error! */ } Options for handling error Abort Ask again Save user data Ask for less Free up something

54 malloc -- What happens? int foo(int n) { int *ip;
ip = (int *) malloc(n * sizeof(int)); if(ip == NULL) { /* Handle Error! */ } ... Stack Heap 40 bytes Data Code

55 calloc() The C library function
void *calloc(size_t nitems, size_t size) allocates the requested memory and returns a pointer to it. Allocates a block of memory for an array of nitems elements, each of them size bytes long, and initializes all its bits to zero.

56 Releasing the Used Space
free (ptr) ; where ptr is a pointer to a memory block which has been already created using malloc() / calloc() / realloc().

57 The Heap What does the heap look like exactly?
Imagine a giant contiguous region of memory This region is segmented into free block and used blocks The free blocks form an explicit, doubly-linked list To allocate a block, we remove it from the list and return a pointer to it To free a block, we insert it back into the list

58 Structures and malloc struct person { char initials[4]; long int ssn;
int height; struct person *father; struct person *mother; } *tom, *bill, *susan;

59 Structures and malloc int main() {
struct person { char initials[4]; long int ssn; int height; struct person *father; struct person *mother; } *tom, *bill, *susan; int main() { tom =(struct person *)malloc( sizeof( struct person ) ); bill=(struct person *)malloc( sizeof( struct person ) ); susan=(struct person *)malloc( sizeof( struct person ) ); strncpy(tom->initials, "tj“, 2); tom->ssn = ; tom->father = bill; tom->mother = susan; susan->height = 68; printf(“\nTom's mother's height is: %d", tom->mother->height); }

60 Realloc ptr = realloc(ptr, num_bytes); What it does (conceptually)
Find space for new allocation Copy original data into new space Free old space Return pointer to new space

61 Realloc ptr in-use Before in-use After ptr

62 Realloc: What might happen
ptr Before unused ptr After

63 void read_array (int *a, int n) ;
int sum_array (int *a, int n) ; void wrt_array (int *a, int n) ; int main () { int *a, n; printf (“Input n: “) ; scanf (“%d”, &n) ; a = calloc (n, sizeof (int)) ; read_array (a, n) ; wrt_array (a, n) ; printf (“Sum = %d\n”, sum_array(a, n); }

64 void read_array (int *a, int n) {
int i; for (i=0; i<n; i++) scanf (“%d”, &a[i]) ; } void sum_array (int *a, int n) { int i, sum=0; sum += a[i] ; return sum; void wrt_array (int *a, int n) {

65 Arrays of Pointers Array elements can be of any type
array of structures array of pointers

66 int main (void) { char word[MAXWORD]; char * w[N]; /* an array of pointers */ int i, n; /* n: no of words to sort */ for (i=0; scanf(“%s”, word) == 1); ++i) { w[i] = calloc (strlen(word)+1, sizeof(char)); if (w[i] == NULL) exit(0); strcpy (w[i], word) ; } n = i; sortwords (w, n) ; wrt_words (w, n); return 0;

67 Input : A is for apple or alphabet pie which
Input : A is for apple or alphabet pie which all get a slice of come taste it and try w A \0 1 i s \0 2 f o r \0 3 a p p l e \0 17 t r y \0

68 void sort_words (char *w[], int n) {
int i, j; for (i=0; i<n; ++i) for (j=i+1; j<n; ++j) if (strcmp(w[i], w[j]) > 0) swap (&w[i], &w[j]) ; } void swap (char **p, char **q) { char *tmp ; tmp = *p; *p = *q; *q = tmp;

69 Before swapping w w[i] f o r \0 a p p l e \0 w[j]

70 After swapping w w[i] f o r \0 a p p l e \0 w[j]

71 Example #include <stdio.h> printf("Input heights for %d
int main() { int i,N; float *height; float sum=0,avg; printf("Input the number of students. \n"); scanf("%d",&N); height=(float *) malloc(N * sizeof(float)); printf("Input heights for %d students \n",N); for(i=0;i<N;i++) scanf("%f",&height[i]); sum+=height[i]; avg=sum/(float) N; printf("Average height= %f \n", avg); } Input the number of students. 5 Input heights for 5 students Average height=

72 2d arrays and pointers Recall that when we declare a two-dimensional array, we can think of it as an array of arrays. For example, if we have the following array declaration, int data[3][4]; we can think of this as an array with three members, each of which is an array of four ints. We can visualize it like this:

73 The address of the beginning of the entire array is the same as the address of the first row of the array, which is the address of the first element of the first row. However, to get to the first row we must dereference the array name and to get the value of the first element of the first row we must dereference twice int sales[2][3] = { {1, 2, 3}, {9, 10, 11} }; printf("address of data is %p\n", sales); printf("address of row 0 of data is %p\n", *sales); printf("the value of sales[0][0] is %d\n", **sales); produces address of data is 0x7fffffed8140 address of row 0 of data is 0x7fffffed8140 the value of sales[0][0] is 1

74 2d arrays *(array_name + row) + column
The general form for getting the address of any element of any row is *(array_name + row) + column For example, when we write *(data + 1) + 2, we are saying “add the size of one row to the address of data, get the address of this, then add the size of two elements of a row to this”.

75 Pointer Indirection (Pointers to Pointers)
a=58; p=&a; q=&p; a = 58 *p = 58 **q = 58

76 Pointer to Pointer Example: int **p;
p=(int **) malloc(3 * sizeof(int *)); p[0] p int ** int * p[1] int * int * p[2]

77 2d array int AA[MAX][15] A two dimensional array is considered to be a one dimensional array of rows, which are, themselves, one dimensional arrays. The rows are stored in sequence, starting with row 0. AA[0] is stored first, then AA[1], then AA[2], and so on to AA[MAX-1]. Each of these ``elements'' is an array. The same is true for higher dimensional arrays. A n-dimensional array is considered to be a one dimensional array whose elements are, themselves, arrays of dimension.

78

79 2d array Recall that an array name (without an index) represents a pointer to the first object of the array. So the name, AA, is a pointer to the element AA[0]. But, AA[0] is a one dimensional array; so, AA[0] points to the first object in row 0, i.e. AA[0] points to AA[0][0]. AA[k] is the address of AA[k][0]. AA[k] + j points to AA[k][j], and *(AA[k] + j) accesses the value of AA[k][j] .

80 2d array The name, AA points to the first object in this array of arrays, i.e. AA points to the array AA[0]. The addresses represented by AA and AA[0] are the same; however, they point to objects of different types. AA[0] points to AA[0][0], so it is an integer pointer. AA points to AA[0], so it is a pointer to an integer pointer. If we add 1 to AA, the resulting pointer, AA + 1, points to the array AA[1], and AA + k points to the array AA[k]. Adding 1 to AA[0] results in a pointer that points to AA[0][1]

81 Pointer equivalence to 2d arrays

82 Dynamically Allocating 2D Arrays
Can not simply dynamically allocate 2D (or higher) array Idea - allocate an array of pointers (first dimension), make each pointer point to a 1D array of the appropriate size Can treat result as 2D array

83 Dynamically Allocating 2D Array
float **A; /* A is an array (pointer) of float pointers */ int I; A = (float **) calloc(5,sizeof(float *)); /* A is a 1D array (size 5) of float pointers */ for (I = 0; I < 5; I++) A[I] = (float *) calloc(4,sizeof(float)); /* Each element of array points to an array of 4 float variables */ /* A[I][J] is the Jth entry in the array that the Ith member of A points to */

84 Non-Square 2D Arrays No need to allocate square 2D arrays: float **A;
int I; A = (float **) calloc(5, sizeof(float *)); for (I = 0; I < 5; I++) A[I] = (float **) calloc(I+1, sizeof(float));

85 Dynamically Allocating Multidimensional Arrays

86 2-D Array Allocation #include <stdio.h>
#include <stdlib.h> int **allocate(int h, int w) { int **p; int i,j; p=(int **) calloc(h, sizeof (int *) ); for(i=0;i<h;i++) p[i]=(int *) calloc(w,sizeof (int)); return(p); } void read_data(int **p,int h,int w) { int i,j; for(i=0;i<h;i++) for(j=0;j<w;j++) scanf ("%d",&p[i][j]); } Allocate array of pointers Elements accessed like 2-D array elements. Allocate array of integers for each row

87 2-D Array: Contd. int main() void print_data(int **p,int h,int w) { {
int i,j; for(i=0;i<h;i++) for(j=0;j<w;j++) printf("%5d ",p[i][j]); printf("\n"); } int main() { int **p; int M,N; printf("Give M and N \n"); scanf("%d%d",&M,&N); p=allocate(M,N); read_data(p,M,N); printf("\n The array read as \n"); print_data(p,M,N); } Give M and N 3 3 1 2 3 4 5 6 7 8 9 The array read as

88 2d arrays and pointers Recall that when we declare a two-dimensional array, we can think of it as an array of arrays. For example, if we have the following array declaration, int data[3][4]; we can think of this as an array with three members, each of which is an array of four ints. We can visualize it like this:

89 2d arrays *(array_name + row) + column
The general form for getting the address of any element of any row is *(array_name + row) + column For example, when we write *(data + 1) + 2, we are saying “add the size of one row to the address of data, get the address of this, then add the size of two elements of a row to this”.

90 Pointer to Pointer Example: int **p;
p=(int **) malloc(3 * sizeof(int *)); p[0] p int ** int * p[1] int * int * p[2]

91 2d array int AA[MAX][15] A two dimensional array is considered to be a one dimensional array of rows, which are, themselves, one dimensional arrays. The rows are stored in sequence, starting with row 0. AA[0] is stored first, then AA[1], then AA[2], and so on to AA[MAX-1]. Each of these ``elements'' is an array. The same is true for higher dimensional arrays. A n-dimensional array is considered to be a one dimensional array whose elements are, themselves, arrays of dimension.

92

93 2d array Recall that an array name (without an index) represents a pointer to the first object of the array. So the name, AA, is a pointer to the element AA[0]. But, AA[0] is a one dimensional array; so, AA[0] points to the first object in row 0, i.e. AA[0] points to AA[0][0]. AA[k] is the address of AA[k][0]. AA[k] + j points to AA[k][j], and *(AA[k] + j) accesses the value of AA[k][j] .

94 2d array The name, AA points to the first object in this array of arrays, i.e. AA points to the array AA[0]. The addresses represented by AA and AA[0] are the same; however, they point to objects of different types. AA[0] points to AA[0][0], so it is an integer pointer. AA points to AA[0], so it is a pointer to an integer pointer. If we add 1 to AA, the resulting pointer, AA + 1, points to the array AA[1], and AA + k points to the array AA[k]. Adding 1 to AA[0] results in a pointer that points to AA[0][1]

95 Pointer equivalence to 2d arrays

96 Dynamically Allocating 2D Arrays
Can not simply dynamically allocate 2D (or higher) array Idea - allocate an array of pointers (first dimension), make each pointer point to a 1D array of the appropriate size Can treat result as 2D array

97 Dynamically Allocating 2D Array
float **A; /* A is an array (pointer) of float pointers */ int I; A = (float **) calloc(5,sizeof(float *)); /* A is a 1D array (size 5) of float pointers */ for (I = 0; I < 5; I++) A[I] = (float *) calloc(4,sizeof(float)); /* Each element of array points to an array of 4 float variables */ /* A[I][J] is the Jth entry in the array that the Ith member of A points to */

98 Non-Square 2D Arrays No need to allocate square 2D arrays: float **A;
int I; A = (float **) calloc(5, sizeof(float *)); for (I = 0; I < 5; I++) A[I] = (float **) calloc(I+1, sizeof(float));

99 2-D Array Allocation #include <stdio.h>
#include <stdlib.h> int **allocate(int h, int w) { int **p; int i,j; p=(int **) calloc(h, sizeof (int *) ); for(i=0;i<h;i++) p[i]=(int *) calloc(w,sizeof (int)); return(p); } void read_data(int **p,int h,int w) { int i,j; for(i=0;i<h;i++) for(j=0;j<w;j++) scanf ("%d",&p[i][j]); } Allocate array of pointers Elements accessed like 2-D array elements. Allocate array of integers for each row

100 2-D Array: Contd. int main() void print_data(int **p,int h,int w) { {
int i,j; for(i=0;i<h;i++) for(j=0;j<w;j++) printf("%5d ",p[i][j]); printf("\n"); } int main() { int **p; int M,N; printf("Give M and N \n"); scanf("%d%d",&M,&N); p=allocate(M,N); read_data(p,M,N); printf("\n The array read as \n"); print_data(p,M,N); } Give M and N 3 3 1 2 3 4 5 6 7 8 9 The array read as

101 Array Pointers To declare a pointer to an array type, you must use parentheses int (* arrPtr)[10] ; // A pointer to an array of // ten elements with type int

102 int a[10]; Declares and allocates an array of int(s).
Declares and allocates an array of pointers to int. Each element must be dereferenced individually. int (*a)[10]; Declares (without allocating) a pointer to an array of int(s). The pointer to the array must be dereferenced to access the value of each element. int a[10]; Declares and allocates an array of int(s).

103 Array Pointers int (* arrPtr)[10] ; // A pointer to an array of 10 elements // with type int if we assign it the address of an appropriate array, *arrPtr yields the array, and (*arrPtr)[i] yields the array element with the index i.

104 int matrix[3][10]; // Array of 3 rows, each with 10 columns
int matrix[3][10]; // Array of 3 rows, each with 10 columns. // The array name is a pointer to the first row. arrPtr = matrix; // Let arrPtr point to the first row of the matrix. (*arrPtr)[0] = 5; // Assign the value 5 to the first element of the first row. arrPtr[2][9] = 6; // Assign 6 to the last element of the last row. ++arrPtr; // Advance the pointer to the next row. (*arrPtr)[0] = 7; // Assign 7 to the first element of the second row. (*arrPtr)[0] = 7; // Assign value 7 to the first element of the second row.

105 sizeof a = 80 *a[0] = 1 *a[1] = 2 *a[2] = 3 int main ( ) { int i; int * a[10] ; printf (“sizeof a = %d\n” , sizeof(a)); int x=1, y=2, z=3; a[0] = &x; a[1] = &y; a[2] = &z; for (i=0; i<10; i++) printf ("*a[%d] = %d\n", i, *(a[i])) ; }

106 int main ( ) { int i; int (*b)[10] ; printf (“sizeof b = %d\n”, sizeof(b)); b = malloc (10*sizeof(int)) ; printf ("b = %p\n", b) ; printf ("b+1 = %p\n", b+1) ; for (i=0; i<10; i++) { (*b)[i] = i; printf (“(*b)[%d] = %d\n",i, (*b)[i]) ; } sizeof b = 8 b = 0x601010 b+1 = 0x601038 (*b)[0] = 0 (*b)[1] = 1 (*b)[2] = 2 (*b)[3] = 3 (*b)[4] = 4


Download ppt "Pointers."

Similar presentations


Ads by Google