Arrays an array of 5 ints is filled with 3,2,4,1,7

Slides:



Advertisements
Similar presentations
Memory allocation CSE 2451 Matt Boggus. sizeof The sizeof unary operator will return the number of bytes reserved for a variable or data type. Determine:
Advertisements

Informática II Prof. Dr. Gustavo Patiño MJ
1 Pointers A pointer variable holds an address We may add or subtract an integer to get a different address. Adding an integer k to a pointer p with base.
Pointers and dynamic objects COMP171 Fall Pointers and dynamic objects/ Slide 2 Topics * Pointers n Memory addresses n Declaration n Dereferencing.
Starting out with C++1 Chapter 9 – Pointers Getting the address of a Variable Why do we have pointers? Indirection – difference between –Will you go out.
Pointers. Addresses in Memory When a variable is declared, enough memory to hold a value of that type is allocated for it at an unused memory location.
Review on pointers and dynamic objects. Memory Management  Static Memory Allocation  Memory is allocated at compiling time  Dynamic Memory  Memory.
Memory and C++ Pointers.  C++ objects and memory  C++ primitive types and memory  Note: “primitive types” = int, long, float, double, char, … January.
1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation –The new operator –The delete operator –Dynamic.
1 Procedural Concept The main program coordinates calls to procedures and hands over appropriate data as parameters.
Prof. amr Goneid, AUC1 CSCE 110 PROGRAMMING FUNDAMENTALS WITH C++ Prof. Amr Goneid AUC Part 10. Pointers & Dynamic Data Structures.
CS 11 C track: lecture 5 Last week: pointers This week: Pointer arithmetic Arrays and pointers Dynamic memory allocation The stack and the heap.
Variables, Functions & Parameter Passing CSci 588 Fall 2013 All material not from online sources copyright © Travis Desell, 2011.
Addresses in Memory When a variable is declared, enough memory to hold a value of that type is allocated for it at an unused memory location. This is.
February 11, 2005 More Pointers Dynamic Memory Allocation.
1 C++ Classes and Data Structures Jeffrey S. Childs Chapter 4 Pointers and Dynamic Arrays Jeffrey S. Childs Clarion University of PA © 2008, Prentice Hall.
C++ Data Types Structured array struct union class Address pointer reference Simple IntegralFloating char short int long enum float double long double.
Dynamic Memory Allocation. Domain A subset of the total domain name space. A domain represents a level of the hierarchy in the Domain Name Space, and.
Dynamic memory allocation and Pointers Lecture 4.
Current Assignments Start Reading Chapter 6 Project 3 – Due Thursday, July 24 Contact List Program Homework 6 – Due Sunday, July 20 First part easy true/false.
Copyright 2005, The Ohio State University 1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation.
Week 2. Functions: int max3(int num1, int num2, int num3) {int result; result = max(max(num1,num2),num3); return result; } //max3.
Computer Organization and Design Pointers, Arrays and Strings in C Montek Singh Sep 18, 2015 Lab 5 supplement.
CS415 C++ Programming Takamitsu Kawai x4212 G11 CERC building WV Virtual Environments Lab West Virginia University.
12/23/2015Engineering Problem Solving with C++, second edition, J. Ingber 1 Engineering Problem Solving with C++, Etter/Ingber Chapter 9 An Introduction.
Arrays  an array of 5 ints is filled with 3,2,4,1,7 int a[5] = {3,2,4,1,7}; // note squiggly brackets  an array of 3 floats is filled with 3.2,1.4,0;
1 Recall that... char str [ 8 ]; str is the base address of the array. We say str is a pointer because its value is an address. It is a pointer constant.
Lecture 01d: C++ review Topics: functions scope / lifetime preprocessor directives header files C structures ("simple classes")
CMSC 341 Lecture 2 – Dynamic Memory and Pointers (Review)
Computer Organization and Design Pointers, Arrays and Strings in C
Popping Items Off a Stack Using a Function Lesson xx
Overview 4 major memory segments Key differences from Java stack
Introduction to Programming
Pointers and Memory Overview
Checking Memory Management
Student Book An Introduction
Dynamic Memory CSCE 121 J. Michael Moore.
Chapter 10: Pointers Starting Out with C++ Early Objects Ninth Edition
Pointers and Dynamic Variables
Dynamically Allocated Memory
Data Structures with C++
Dynamic Memory Allocation Reference Variables
CSC 253 Lecture 8.
C – Scope, Lifetime, and the Stack
CSC 253 Lecture 8.
Overview 4 major memory segments Key differences from Java stack
Pointers and dynamic objects
Chapter 15 Pointers, Dynamic Data, and Reference Types
Overview of Memory Layout in C++
Pointers, Dynamic Data, and Reference Types
Dynamic Memory A whole heap of fun….
Dynamic Memory Allocation
Chapter 15 Pointers, Dynamic Data, and Reference Types
Given the code to the left:
Dynamic Memory A whole heap of fun….
What about multi-dimensional arrays?
Data Structures with C++
C++ Pointers and Strings
Dynamic Memory A whole heap of fun….
Dynamic Memory.
Lists.
COP 3330 Object-oriented Programming in C++
CS31 Discussion 1D Winter19: week 4
Pointers and dynamic objects
CS31 Discussion 1H Fall18: week 7
C++ Pointers and Strings
Dynamic Memory CSCE 121.
Pointers, Dynamic Data, and Reference Types
SPL – PS2 C++ Memory Handling.
Presentation transcript:

Arrays an array of 5 ints is filled with 3,2,4,1,7 int a[5] = {3,2,4,1,7}; // note squiggly brackets an array of 3 floats is filled with 3.2,1.4,0; float b[3] = {3.2,1.4}; makes an array of spaces for 7 ints; the array at 3 holds 24, rest holds nothing (if you print, will print out whatever happens to be leftover there) int c[7]; c[3] = 24; cout << c[2] << endl; // might print -328918973 Makes an array of 3 ints, holding 4,1,2 int d[] = {4,1,2}; Next: int d[]; d[0] = 4; yeah, no. d[] is indicating that we need an address for an array of ints. But we haven’t actually made an array of ints. We don’t know how many spaces to set aside, and equally, we don’t know what the address of the array should be. Can we set aside space? Hold that thought…

Question Given: int arr[4] = {2,16,8,23}; If we know the size (number of bits) of ints, and that arrays occur sequentially in memory, what is the absolute minimum we need to know about the array to find any of the values in the array?

Passing arrays into functions: Given the following array: int x[4000000]; for (int i = 0; i < 4000000; i++) { x[i] = i; } In terms of memory space, do we want to make a new, local copy of the array when we call a function? To get the address of the array (aka a pointer to the array): int arr[4] = {3,2,1,4}; cout << &arr[0] << endl; //address of first value in array cout << arr << endl; //same value, address of array, of where first value in array is

Arrays and Functions: int main() { } // main Note: no straightforward way of getting size of an array. Easiest way: pass the length of the array along with a pointer to the array (aka the address of the array), e.g., int main() { int x[4]= {3,2,4,1}; double k = getAverage(&x[0],4); // gets the address of the first value in the array // Or double l = getAverage(x,4); // the address of the first value in the array cout << k << endl; } // main Function definition: double getAverage(int *arr, int size) // a pointer, a variable that holds an address { int sum = 0; for (int i = 0; i < size; i++) { sum += arr[i]; // now, in essence, the value at (the address of arr + i) } //for double avg = double(sum) / size; return avg; }//main Alternative: double getAverage(int arr[], int size) { //holds address of the first value in the array }

sizeof() Can use sizeof() to get the length of something in bytes int arr[4] = {3,2,7,1}; cout << sizeof(arr)/4 << endl; // prints 4 float y[3]; cout << sizeof(y)/4 << endl; // prints 3 double z[7]; cout << sizeof(z)/4<< endl; // prints 14 (why?) Problem: different compilers make types different sizes For years, 2 bytes was standard for an int Now many have 4 bytes Instead: cout << sizeof(arr)/sizeof(int) << endl; This doesn’t work on pointers! (when you pass an address into a function!) Pass in the size if you need the array’s size in a function.

Arrays and functions (cont): What if I did this: int main() { int arr[7] = {10,20,30,40,50,60,70}; func(arr,7); func(&arr[0],7); func(&arr[2],5); return 0; } void func(int *x, int size) { for (int i = 0; i < size; i++) { cout <<x[i] << “, “; cout << endl; return;

Dynamically allocated arrays What if we don’t know the size of the array when we write the code? Maybe the array size is random Maybe we’re reading in data from a file What if we want to create an array inside of a function and then have the array continue to exist after the function is done running? After the volcano erupts and destroys the function island?? We can “Dynamically allocate” the array Short version: we create a variable that will hold the address of the first value of an array (at some point) Then, when we want to, we set aside space in memory for the array and place the address of the first value of that space into our variable.

Memory management: Two types of memory: stack and heap Stack – compiler controls E.g., int main() { func(3); cout << k << endl; //what is printed here? Why? return 0; } void func(int x) { int k = pow(2,x); return; Heap (this is new to c++): We control!! We purposely and explicitly put things in the heap part of memory. We need the address of where we put it in the heap! They continue to exist in that heap part of memory until we explicitly get rid of them

New (puts things on the heap) new int; // sets aside memory on the heap for an int (but no variable points to it // this is useless on its own! // new returns the address of that space in memory _____________________________________________________ int *x; // just sets aside space for an address that will hold an int – just the space for the address! x = new int; // now x points to (holds the address of) an int in memory (on the heap) *x = 34; // now the x points to 34; meaning that at the address x holds, there’s a 34 NOTE: you can combine into one step: int *x = new int; What if there’s not enough space on the heap? int *x; if( !(x = new int )) { cout << "Error: out of memory." <<endl; // checking to see if there’s space on the heap exit(1); } //if else { *x = 2; } //else

delete (takes things off the heap) And when you’re done with it… you want to remove it from the heap Delete: frees up the space on the heap: int *x; if( !(x = new int )) { cout << "Error: out of memory." <<endl; // checking to see if there’s space on the heap exit(1); } //if else { *x = 2; } //else delete x; //deallocates the space in memory

What about arrays? int *x = NULL; // Pointer initialized with null (default is undefined) cout << “Enter the number of numbers you want” << endl; int y; cin >> y; x = new int[y]; // Request memory on heap for space for y ints (sequentially) for (int k = 0; k < y; k++) { x[k] = k; } //for And now to free an array? delete [] x; //delete x; - why not? It compiles…

Returning an array int * createArray(int size); int main() { int *a; //a holds an address that points to an int (or the first in a list of ints) a = createArray(4); for (int x = 0; x < 4; x++) { cout << a[x] << endl; } //for return 0; }//main int *createArray(int size) // what is returned??? { int *r = new int[size]; // This array had to be put on the heap. r[0] = 3; r[1]= 2; r[2] = 4; r[3] = 1; return r; // or return &r[0]; } //createArray

Stack vs Heap Heap (memory in a different location) Stack (Memory) Temporary memory storage for variables associated with each function When a function is called – its variables are pushed onto the top of the stack When the function ends – all of its variables are popped from the top of the stack Stack grows and shrinks as function variables are pushed and popped No need (or ability) to manage memory Stack has size limits Stack variables only exist while the function created is pushed on the stack Nice and fast Heap (memory in a different location) not managed automatically Larger than the stack Variables in heap can be accessed globally (if we keep track of their address on the heap) Slower to access Less efficient than the stack Manually allocate space for variables on the heap and then free them when their use is done

What does this give you? int main(){ int *ar2 = func1(4); cout << ar2 << endl; for (int k = 0; k < 4; k++) { cout << ar2[k] << ", "; } cout << endl; return 0; int *func1(int x) { int arr[x]; for (int i = 0; i<x; i++) { arr[i] = pow(i,2); return arr;

Try: void arrfunc1(int *arrx, int &num) { #include <iostream> for(int i = 0; i< 3; i++) { num += arrx[i]; } #include <iostream> #include <stdlib.h> using namespace std; void arrfunc1(int arr[], int &num); int main(){ int a[] ={12,2,3,18,20,4,7,22,3}; //indices: 0 1 2 3 4 5 6 7 8 int tot = 0; arrfunc1(&a[3],tot); cout << tot << endl; return 0; }

Challenge!!: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 k a p d e b m c u g h s i n void arrfunc1(char *arrx, char arry[ ]) { for(int i = 0; i< 3; i++) { arry[i] = arrx[i]; } char *arrfunc2(char arr[ ], int &len) { int newlen = len/2; char *arr2 = new char[newlen]; for (int i = 3; i <= len-3; i+=6) { arrfunc1(&arr[i], &arr2[ (i-3)/2 ]); len = newlen; return arr2; #include <iostream> #include <stdlib.h> #include <string.h> using namespace std; void arrfunc1(char arr[], char arr2[]); char *arrfunc2(char arr[], int &len); int main(){ char a[ ] = {'k','a','p',‘d',‘e',‘b','m','a','c',‘u',‘g',‘g','h','p','s',‘i',‘n',‘g'}; //indices: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 int len = 18; char *b = arrfunc2(a,len); for (int i = 0; i < len; i++) { cout << b[i] << " "; } cout << endl; return 0;

*x: X is a pointer. X holds the address of something else. Thus it must be made to point to: A: SOMETHING THAT EXISTS (you’ve got to get the address of it): int y = 3; int *x; x = &y; // x now points to y – holds the address of y Or B: SOMETHING YOU CREATE (using new): x = new int[4]; //x now holds the memory location of space for 4 ints, technically the address of the first space in the series of 4 consecutive ints (this address is in the heap) x is a pointer, or address holder. Somehow, somewhere, the address must come to be before x can hold that address new always returns an address in memory! And if something is new-ly created, it should be delete-d AKA Garbage collection Anything on the heap must be deleted

What about multi-dimensional arrays? int **x = NULL; // Pointer initialized with null x = new int *[4]; // Allocate memory on heap for a 4x3 array for (int i = 0; i < 4; i++) { array of x[i] = new int[3]; addresses } //for for (int i = 0; i < 4; i++) { for (int j = 0; j < 3; j++) { x[i][j] = i+j; cout << x[i][j]; cout << endl; X 0 1 2 1 2 3 2 3 4 3 4 5

How about deleting? int **x = NULL; // Pointer initialized with null x = new int *[4]; // Allocate memory on heap for a 4x3 array for (int i = 0; i < 4; i++) { x[i] = new int[3]; } //for for (int j = 0; j < 3; j++) { x[i][j] = i+j; Why can’t we just do this? delete [] x; // compiles just fine…

Deleting a multi-dimensional array int **x = NULL; // Pointer initialized with null x = new int *[4]; // Allocate memory on heap for a 4x3 array for (int i = 0; i < 4; i++) { x[i] = new int[3]; } //for delete [] x[i]; delete [] x;

Quick: int x = 3; int y = x; int *z = &x; cout << “x is “ << x <<endl; cout << “ y is “ << y << endl; cout << “ z is “ << *z << endl; x += 4; Can I do this? z = 3;