Download presentation
Presentation is loading. Please wait.
Published byEverett Sims Modified over 9 years ago
1
CSE 2341 Honors Professor Mark Fontenot Southern Methodist University Note Set 04
2
Overview 2D arrays Pointers
3
2D Arrays 20 x 20 grid of integers access each element using 2 subscripts – cout << data[1][2]; – cin >> data[2][10]; Don’t make the mistake of – cout << data[1, 2]; int data[20][20];
4
Initializing 2D Arrays int data[2][3] = { {1, 3, 5}, {2, 4, 6} }; 1 3 5 2 4 6 2 rows 3 columns
5
Initializing 2D Arrays 1 3 0 2 0 0 2 rows 3 columns int data[2][3] = { {1, 3}, {2} };
6
Example Find row with largest sum int data[5][6] = {{10, 12, 4, 5, 13, 17}, {19, 21, -3, 1, 2, 18}, {-9, 14, 15, 99, 1, 3}, {1, 2, 33, 4, 5, 6}, {100, -1, -1, 1, -1, 1}};
7
Passing Arrays to Functions 1D Array – Don’t put anything in [] of function prototype or function header 2D array – Provide size of 2 nd dimension (num columns) in function prototype and function header int foo (int arr[]); int x[5]; foo(x); int bar (int arr[][5]); int y[5][6]; bar(y);
8
2D array as matrix Write a program to read 2 matrices (of compatible size) out of a file and add them together.
9
Pointers - Background Each storage location in main memory is identifiable by a memory address. – How the computer handles storage and retrieval Every C++ variable has a memory address Retrieve the address via the & operator (address-of) int x = 3; cout << x << endl; //value stored in x cout << &x << endl; //address of where x is stored
10
Pointer A pointer is a variable that store the address of a memory location of a particular type Pointer is declared with the *. – Does not distribute to all variables being declared in a single statement… int* x, y, z;//only x is ptr The * operator allows access to the memory location. – Doesn’t always have to be from a pointer. int x = 10; int* ptr; ptr = &x; cout << *ptr << endl; You can declare a pointer to any data type (including void).
11
Problems with Pointers Uninitialized pointers – pointer contains an invalid memory address due to lack of initialization Dangling pointers – pointer was valid at one point, but has become invalid
12
Passing Pointers to Functions int myFunction (int*); //indicate a pointer will be passed int main () { int value = 3; int* v; v = &value; myFunction(v); myFunction(&value); //… } If the value pointed to by the function parameter, will value be changed as well? Why or why not?
13
Ignore Software Engineering Observation 8.1 of text. That’s just dumb. Read Section 8.5 for reasonable and non-dumb solution!
14
?
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.