cs31 lecture 9

0 11 even more on pointers remember the memory

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: ble Example: int a = 0; 11 Even more on pointers Remember the memory example, for a reference M[5] is the content of the cell 5 5 is the address of cell 5 With pointers, use the symbol * to refer to the content of memory Example: int a = 0; int* b = &a; // b contains the address of a. int c = *b; // c contains 0, the content of a. 12 An example with pointers int main() { int a = 0; int* b = &a; std::cout << a << std::endl; std::cout << b << std::endl; std::cout << *b << std::endl; *b = 42; std::cout << a << std::endl; b = b + 1; std::cout << b << std::endl; } 13 Pointers and arrays An array is manipulated as the address of its first element Two equivalent syntax using pointers: *a and a[0] Two equivalent syntax using pointers: *(a+1) and a[1] Examples: int a[10]; int* b; b = a; // b contains the address of the first element14 Dynamic array allocation in C Malloc: assign a contiguous zone in memory of size ‘size’, return the address of the first element Example: int* a = (int*) malloc(4 * sizeof(int)); // sizeof(type) returns the size in byte of an element of type ‘type’. Realloc: extend/shrink a contiguous zone in memory of size ‘size’, return the address of the first element (can be different) Example: int* b = realloc(a, 8 * sizeof(int)); Free: free the contiguous memory zone starting at ‘ptr’ 15 Some advices and typical pitfalls To each malloc there should be a free associated Typical pitfall: forget to free data (“memory leak”) Pointer arithmetic should be done with extreme...
View Full Document

This note was uploaded on 04/03/2014 for the course CS 31 taught by Professor Melkanoff during the Fall '00 term at UCLA.

Ask a homework question - tutors are online