Date post: | 16-Dec-2015 |
Category: |
Documents |
Upload: | ambrose-lester-thompson |
View: | 218 times |
Download: | 1 times |
pointer, malloc and realloc
1
Name entered was 6 char, not enough space to put null terminator
2
Array of char
3
Pointer to array of char
3.cpp(15) : error C2440: '=' : cannot convert from 'int' to 'int *' 4
Pointer to array name[] vs Pointer to variable age (wrong version)
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
Access address and value pointed by pointer to array name[]Access address and value pointed by pointer to variable age
7
strlen()
8
nameptr points to an empty offset (with size 5 bytes)
allocate new memory using malloc, determine no of offset by strlen
name a z l a n
[0] [1] [2] [3] [4]
nameptr
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 a z l a n
[0] [1] [2] [3] [4]
nameptr a z l a n
10
Null terminator
nameptr
a z l a n
[0] [1] [2] [3] [4]
\0
[5]
Use for loop to go to each offset
11
a z l a n
[0] [1] [2] [3] [4]nameptr
Go to the next offset
nameptr++a z l a n
[0] [1] [2] [3] [4]
[0] [1] [2] [3]
nameptr++ will makes nameptr point to the next offset
12
a z l a n
[0] [1] [2] [3] [4]name a z l a n
[0] [1] [2] [3] [4]nameptr
12ff5
8
12ff4
c
3631
50
3631
51
3631
52
3631
53
3631
54
12ff5
9
12ff5
a
12ff5
b
12ff5
c
&name = &name[0] = 12ff58
Line 16, create 1 byte x 5 offsetLine 17, copy string from name to nameptr
Check the address for each array name[] element and nameptr offset
13
a z l a n
[0] [1] [2] [3] [4]name
12ff5
8
12ff5
9
12ff5
a
12ff5
b
12ff5
c
&name = &name[0] = 12ff58
a z l a n
[0] [1] [2] [3] [4]tempptr
12ff4
c
3631
50
3631
51
3631
52
3631
53
3631
54
[0]
listptr12
ff40
3631
88
**listptr – pointer to pointer
14
[0]
ptr
12ff6
0
364d
68
[0]
3631
80
[0]
3631
50
[0]36
31b0
[1]
3631
b4
[2]
3631
b8
listptr
12ff5
4
realloc() – continue create a new offset, to point to other address
15
3631
e8
3631
ec
3631
f0
listptr
12ff1
4
a
[0]
ptr
3631
50
l
[1]
3631
51
i
[2]
3631
52
c
[0]
3631
b0
h
[1]
3631
b1
o
[2]
3631
b2
n
[3]
3631
b3
g
[4]
3631
b4
m
[0]
3632
20
u
[1]
3632
21
t
[2]
3632
22
h
[3]
3632
23
u
[4]
3632
24
[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