Presentation is loading. Please wait.

Presentation is loading. Please wait.

Pointer, malloc and realloc 1. Name entered was 6 char, not enough space to put null terminator 2 Array of char.

Similar presentations


Presentation on theme: "Pointer, malloc and realloc 1. Name entered was 6 char, not enough space to put null terminator 2 Array of char."— Presentation transcript:

1 pointer, malloc and realloc 1

2 Name entered was 6 char, not enough space to put null terminator 2 Array of char

3 3 Pointer to array of char

4 3.cpp(15) : error C2440: '=' : cannot convert from 'int' to 'int *' 4 Pointer to array name[] vs Pointer to variable age (wrong version)

5 4.cpp(14) : warning C4313: 'printf' : '%d' in format string conflicts with argument 1 of type 'int *' 5 Pointer to array name[] vs Pointer to variable age (correct version)

6 6 Access address and value pointed by pointer to array name[] Access address and value pointed by pointer to variable age

7 7 strlen()

8 8 nameptr points to an empty offset (with size 5 bytes) allocate new memory using malloc, determine no of offset by strlen name azlan [0][1][2][3][4] nameptr

9 9 char *strcpy(char *destination, const char *source); The argument order mimics that of an assignment: destination "=" source. The return value is destination strcpy() – copy value from array to offset name azlan [0][1][2][3][4] nameptr azlan

10 10 Null terminator nameptr azlan [0][1][2][3][4] \0 [5] Use for loop to go to each offset

11 11 azlan [0][1][2][3][4] nameptr Go to the next offset nameptr++ azlan [0][1][2][3][4] [0][1][2][3] nameptr++ will makes nameptr point to the next offset

12 12 azlan [0][1][2][3][4] name azlan [0][1][2][3][4] nameptr 12ff58 12ff4c 363150363151363152363153363154 12ff5912ff5a12ff5b12ff5c &name = &name[0] = 12ff58 Line 16, create 1 byte x 5 offset Line 17, copy string from name to nameptr Check the address for each array name[] element and nameptr offset

13 13 azlan [0][1][2][3][4] name 12ff5812ff5912ff5a12ff5b12ff5c &name = &name[0] = 12ff58 azlan [0][1][2][3][4] tempptr 12ff4c 363150363151363152363153363154 363150 [0] listptr 12ff40 363188 **listptr – pointer to pointer

14 14 [0] ptr 12ff60 364d68 [0] 363180 [0] 363150 364d68 [0] 3631b0 363180 [1] 3631b4 363150 [2] 3631b8 listptr 12ff54 realloc() – continue create a new offset, to point to other address

15 15 363150 3631e8 3631b0 3631ec 363220 3631f0 listptr 12ff14 a [0] ptr 363150 l [1] 363151 i [2] 363152 c [0] 3631b0 h [1] 3631b1 o [2] 3631b2 n [3] 3631b3 g [4] 3631b4 m [0] 363220 u [1] 363221 t [2] 363222 h [3] 363223 u [4] 363224 [0][1][2] when offset=0 when offset=1 when offset=2 Line 11-create new malloc, line 12-copy value from name[] to ptr, line 18-create new offset, line 15 and 19-offset points to where ptr points


Download ppt "Pointer, malloc and realloc 1. Name entered was 6 char, not enough space to put null terminator 2 Array of char."

Similar presentations


Ads by Google