Download presentation
Presentation is loading. Please wait.
Published byPhilomena Brown Modified over 8 years ago
1
1 ร. ศ. ดร. สุเทพ มาดารัศมี Understanding Pointers in C Chapter 10 of Programming with C Book
2
2 Basic Notes int *x; float *y; float j = 200.0; int i = 50; -means x is of type pointer using 4 bytes expected to point to integer value. -Means y is also type pointer using 4 bytes, expected to point to float value. &i - means address of i. -In this case it is A205 -x = &i; y = &j; xA205A193 A194 A195 A196 yA201A197 A198 A199 A200 j200.0A201 A202 A203 A204 i50A205 A206 *x - means go to that pointed by x. printf( “ %d ”, *x) 50 *y = 30.5; 30.5
3
3 Can Memorize for Functions: Variables When calling a function where variable’s value will change: Function definition will have * before the variable name everywhere in the function. Caller will have ‘&’ before the variable
4
4 Memory Values
5
5 Memorize for Functions: Arrays When calling a function where Array (Name[30]) is sent as parameter: 1. Function definition will have array appear as char Name[] which means char *Name 2. Caller will NOT have ‘&’ before Array name. Array Name alone means its address. TotalScore means &TotalScore[0] int *Score &TotalScore
6
6 17 18 19 16 20 5 int *Score * &TotalScore A100 5 0 17 1 18 2 19 34 20 5
7
7 More Rules int *Score &TotalScore *Score + i which is *(Score + i) TotalScore[2] = 32 is viewed as *TotalScore + 2 = 32 which is *(&TotalScore +2) = 32 When C sees Score[i] or TotalScore[2] it converts the code to: *Score + i and *TotalScore + 2. Now, there is a rule about arrays that if the array name such as TotalScore is mentioned alone without an index, it means the address of TotalScore or &TotalScore. Thus, *TotalScore + 2 is same as *(&TotalScore +2). Score[i] is *Score + i or *(Score + i)
8
8 17 18 19 16 20 5 int *Score * &TotalScore A100 5 0 17 1 18 2 19 34 20 5 *Score + i which is *(Score + i) TotalScore[2] = 32 is viewed as *TotalScore + 2 = 32 which is *(&TotalScore +2) = 32 32
9
9 2-D Arrays In main: In GetInput: Name[3][2] is ‘T’ is *(&Name +3*40+2) is ‘T’. char *Name[40] – pointer to 40 characters at a time or 40 bytes Name[2] is *(Name + 2) is *(A100 + 2*40) is *(A180), meaning “PAM” A100 why have &
Similar presentations
© 2024 SlidePlayer.com Inc.
All rights reserved.