| | 113 | |
| | 114 | {{{ |
| | 115 | #!C |
| | 116 | /* The variable answer_p is a constant and can't change, but the pointer address can be changed. */ |
| | 117 | const char *answer_p = "Forty-Two"; |
| | 118 | |
| | 119 | /* If we want to have the inverse to this, we need to put the const AFTER the *, so: */ |
| | 120 | char *const answer_p = "Forty-Two"; |
| | 121 | /* Now the pointer can't change the address value, but the data (Forty-Two) can be changed */ |
| | 122 | |
| | 123 | /* Finally, we can set both in constant with something like: */ |
| | 124 | const char *const answer_p = "Forty-Two"; |
| | 125 | }}} |
| 200 | | With pointers you can modify directly the data of a variable (see #functions) |
| | 222 | With pointers you can modify directly the data of a variable (see the '''functions''' section) |
| | 223 | |
| | 224 | You can access to a lot more fast way to structure elements and other big pieces that are inside big ones, so you can optimize your code with the correct usage of pointers, |
| | 225 | |
| | 226 | If you want to have a pointer to an array, you need to point to the first array of the variable, so: |
| | 227 | {{{ |
| | 228 | #!C |
| | 229 | /* array of 5 elements */ |
| | 230 | char arr[5]; |
| | 231 | |
| | 232 | /* pointer 'arr_p' to the array 'arr' |
| | 233 | char *arr_p = &arr[0]; |
| | 234 | |
| | 235 | *(array_p + 1) /* Equivalent */ |
| | 236 | (*array_p + 1 ) /* Not Equivalent */ |
| | 237 | }}} |
| | 238 | |
| | 294 | === Optimizations === |
| | 295 | |
| | 296 | An array do increments of the array level in order to search/find something, by using pointers is a lot faster than generate an index operation, for example: |
| | 297 | {{{ |
| | 298 | #!C |
| | 299 | while ((*array_p) != 0) |
| | 300 | ++array__p; |
| | 301 | }}} |
| | 302 | |
| | 303 | Imagine a structure of 226 bytes long, for example, that's a lot of data to move around, so you can declare an array of pointers: |
| | 304 | {{{ |
| | 305 | #!C |
| | 306 | struct mailing { |
| | 307 | ... |
| | 308 | } list[MAX_ENTRIES]; |
| | 309 | |
| | 310 | struct mailing *list_p[MAX_ENTRIES]; |
| | 311 | |
| | 312 | for (current... |
| | 313 | list_p[current] = &list[current]; |
| | 314 | }}} |
| | 315 | Now you have to move only 4-byte around, instead of 226 all the time |
| | 316 | |
| | 317 | |
| | 318 | |
| | 319 | |
| | 320 | |
| | 321 | |
| | 322 | |