{[ promptMessage ]}

Bookmark it

{[ promptMessage ]}

cs31 lecture 9

0 11 even more on pointers remember the memory

Info icon This 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

{[ snackBarMessage ]}

What students are saying

  • Left Quote Icon

    As a current student on this bumpy collegiate pathway, I stumbled upon Course Hero, where I can find study resources for nearly all my courses, get online help from tutors 24/7, and even share my old projects, papers, and lecture notes with other students.

    Student Picture

    Kiran Temple University Fox School of Business ‘17, Course Hero Intern

  • Left Quote Icon

    I cannot even describe how much Course Hero helped me this summer. It’s truly become something I can always rely on and help me. In the end, I was not only able to survive summer classes, but I was able to thrive thanks to Course Hero.

    Student Picture

    Dana University of Pennsylvania ‘17, Course Hero Intern

  • Left Quote Icon

    The ability to access any university’s resources through Course Hero proved invaluable in my case. I was behind on Tulane coursework and actually used UCLA’s materials to help me move forward and get everything together on time.

    Student Picture

    Jill Tulane University ‘16, Course Hero Intern