150 likes | 337 Views
pointer, malloc and realloc. Array of char. Name entered was 6 char, not enough space to put null terminator. Pointer to array of char. Pointer to array name[] vs Pointer to variable age (wrong version). 3.cpp(15) : error C2440: '=' : cannot convert from 'int' to 'int *'.
E N D
Array of char Name entered was 6 char, not enough space to put null terminator
Pointer to array name[] vs Pointer to variable age (wrong version) 3.cpp(15) : error C2440: '=' : cannot convert from 'int' to 'int *'
Pointer to array name[] vs Pointer to variable age (correct version) 4.cpp(14) : warning C4313: 'printf' : '%d' in format string conflicts with argument 1 of type 'int *'
Access address and value pointed by pointer to array name[] Access address and value pointed by pointer to variable age
allocate new memory using malloc, determine no of offset by strlen [0] [1] [2] [3] [4] name a z l a n nameptr nameptr points to an empty offset (with size 5 bytes)
strcpy() – copy value from array to offset [0] [1] [2] [3] [4] name a z l a n nameptr a z l a n char*strcpy(char*destination,constchar*source); The argument order mimics that of an assignment: destination "=" source. The return value is destination
Use for loop to go to each offset nameptr [0] [1] [2] [3] [4] [5] a z l a n \0 Null terminator
nameptr++ will makes nameptr point to the next offset Go to the next offset [0] [1] [2] [3] [4] nameptr a z l a n [0] [1] [2] [3] [0] [1] [2] [3] [4] nameptr++ a z l a n
Check the address for each array name[] element and nameptr offset Line 16, create 1 byte x 5 offset Line 17, copy string from name to nameptr [0] [1] [2] [3] [4] [0] [1] [2] [3] [4] name nameptr a z l a n a z l a n 12ff4c 12ff58 12ff59 12ff5a 12ff5b 12ff5c 363150 363151 363152 363153 363154 &name = &name[0] = 12ff58
**listptr – pointer to pointer [0] [1] [2] [3] [4] name a z l a n 12ff58 12ff59 12ff5a 12ff5b 12ff5c &name = &name[0] = 12ff58 [0] [1] [2] [3] [4] tempptr a z l a n 12ff4c 363150 363151 363152 363153 363154 [0] 363150 listptr 12ff40 363188
realloc() – continue create a new offset, to point to other address [0] [1] [2] [0] [0] [0] listptr 364d68 363180 363150 ptr 12ff54 12ff60 3631b0 3631b4 3631b8 364d68 363180 363150
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 [0] [1] [2] a l i when offset=0 ptr 363150 363151 363152 when offset=1 [0] [1] [2] [3] [4] c h o n g when offset=2 3631b0 3631b1 3631b2 3631b3 3631b4 [0] [1] [2] [3] [4] m u t h u 363220 363221 363222 363223 363224 [0] [1] [2] listptr 363150 3631b0 363220 12ff14 3631e8 3631ec 3631f0