1 ร. ศ. ดร. สุเทพ มาดารัศมี Understanding Pointers in C Chapter 10 of Programming with C Book
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 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 Memory Values
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
int *Score * &TotalScore A
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)
int *Score * &TotalScore A *Score + i which is *(Score + i) TotalScore[2] = 32 is viewed as *TotalScore + 2 = 32 which is *(&TotalScore +2) = 32 32
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 *(A *40) is *(A180), meaning “PAM” A100 why have &