Pointers to pointers & multi-dimensional arrays

Slides:



Advertisements
Similar presentations
Dynamic Allocation and Linked Lists. Dynamic memory allocation in C C uses the functions malloc() and free() to implement dynamic allocation. malloc is.
Advertisements

Introduction to C Programming in Unix Environment - II Abed Asi Extended System Programming Laboratory (ESPL) CS BGU Fall 2014/2015 Some slides.
Pointers Discussion 5 Section Housekeeping HW 1 Issues Array Issues Exam 1 Questions? Submitting on Time!
Memory Arrangement Memory is arrange in a sequence of addressable units (usually bytes) –sizeof( ) return the number of units it takes to store a type.
. Plab – Tirgul 5 pointers to pointers, libraries.
. Compilation / Pointers Debugging 101. Compilation in C/C++ hello.c Preprocessor Compiler stdio.h tmpXQ.i (C code) hello.o (object file)
Plab 2003 Exercise 4. Pointers to pointers. Plab 2003 Exercise 4 2 Pointers to pointers (1)int i=3 (2)int j=4; (3)int k=5; 3 i: 4 j: 5 k: ip1: ip2: (4)int.
15213 C Primer 17 September Outline Overview comparison of C and Java Good evening Preprocessor Command line arguments Arrays and structures Pointers.
Arrays and Pointers in C Alan L. Cox
Chapter 0.2 – Pointers and Memory. Type Specifiers  const  may be initialised but not used in any subsequent assignment  common and useful  volatile.
Week 9 Part 1 Kyle Dewey. Overview Dynamic allocation continued Heap versus stack Memory-related bugs Exam #2.
Weeks 5-6 Pointers and Arrays Basic pointer type Pointers and Arrays Address arithmetic Pointer Arrays User-defined data types Structures Unions Pointers.
Functions & Pointers in C Jordan Erenrich
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.
What we will cover A crash course in the basics of C “Teach yourself C in 21 days”
Arrays, Strings, and Memory. Command Line Arguments #include int main(int argc, char *argv[]) { int i; printf("Arg# Contents\n"); for (i = 0; i < argc;
Pointers1 WHAT IS A POINTER? Simply stated, a pointer is an address. A running program consists of three parts: execution stack, code, and data. They are.
Pointers & References. Pointers Pointer arithmetic Pointers and arrays Pointer-related typedef’s Pointers and const References.
Multi-dimensional Arrays and other Array Oddities Rudra Dutta CSC Spring 2007, Section 001.
C Primer Session – 1/25/01 Outline Hello World Command Line Arguments Bit-wise Operators Dynamic Memory / Pointers Function Parameters Structures.
Chapter 5 Pointers and Arrays Ku-Yaw Chang Assistant Professor, Department of Computer Science and Information Engineering Da-Yeh.
C Tutorial - Pointers CS 537 – Introduction to Operating Systems.
1 Memory, Arrays & Pointers. Memory 2 int main() { char c; int i,j; double x; cijx.
1 Memory, Arrays & Pointers. Memory 2 int main() { char c; int i,j; double x; cijx.
CSE 220 – C Programming malloc, calloc, realloc.
CS/COE 0449 (term 2174) Jarrett Billingsley
Pointers verses Variables
Memory allocation & parameter passing
Stack and Heap Memory Stack resident variables include:
Computer Organization and Design Pointers, Arrays and Strings in C
5.13 Recursion Recursive functions Functions that call themselves
C Primer.
Motivation and Overview
Command Line Arguments
Quiz 11/15/16 – C functions, arrays and strings
C Basics.
2-D arrays a00 a01 a02 a10 a11 a12 a20 a21 a22 a30 a31 a32
Arrays in C.
Pointers.
Arrays and Pointers CSE 2031 Fall September 2018.
Lecture 6 C++ Programming
Templates.
Dynamic Memory Allocation
C Passing arrays to a Function
Pointers.
C Programming Language
Pointers Department of Computer Science-BGU יום רביעי 21 נובמבר 2018.
Pointers, Dynamic Data, and Reference Types
Built-In (a.k.a. Native) Types in C++
Dynamic Memory Allocation
Pointers.
Pointers.
Outline Defining and using Pointers Operations on pointers
Pointers The C programming language gives us the ability to directly manipulate the contents of memory addresses via pointers. Unfortunately, this power.
Chapter 16 Pointers and Arrays
Arrays an array of 5 ints is filled with 3,2,4,1,7
Pointers Pointers point to memory locations
Pointer Variables A pointer is a variable that contains a memory address The address is commonly the location of another variable in memory This pointer.
(PART 2) prepared by Senem Kumova Metin modified by İlker Korkmaz
Programming in C Pointers and Arrays.
C Programming - Lecture 5
Arrays and Pointers (part 2)
Functions Reasons Concepts Passing arguments to a function
Arrays and Pointers (part 2)
15213 C Primer 17 September 2002.
Pointers, Dynamic Data, and Reference Types
Pointers.
Memory, Arrays & Pointers
Presentation transcript:

Pointers to pointers & multi-dimensional arrays

Pointers to pointers int i=3; int j=4; int k=5; int *ip1 = &i; int *ip2 = &j; int **ipp = &ip1; 3 i: 4 j: 5 k: ip1: ip2: ipp:

Pointers to pointers int i=3; int j=4; int k=5; int *ip1 = &i; int *ip2 = &j; int **ipp = &ip1; ipp = &ip2; 3 i: 4 j: 5 k: ip1: ip2: ipp:

Pointers to pointers int i=3; int j=4; int k=5; int *ip1 = &i; int *ip2 = &j; int **ipp = &ip1; ipp = &ip2; *ipp = &k; 3 i: 4 j: 5 k: ip1: ip2: ipp:

Reminder – the swap function Does nothing Works void swap(int a, int b) { int temp = a; a = b; b = temp; } int main() { int x, y; x = 3; y = 7; swap(x, y); // now x==3, y==7 } void swap(int *pa, int *pb) {    int temp = *pa;    *pa = *pb;    *pb = temp; } int main() {    int x, y;    x = 3; y = 7;    swap(&x, &y);    // x == 7, y == 3 }  

Pointers to pointers: example //put pointer to an allocated string in pp int allocString( int len, char ** pp) {    char *str = (char*)malloc(len + 1);    if (str==NULL)    {       return 1;    }    *pp = str;    return 0; }

Pointers to pointers: example // copy a string using "allocString" void main() {    char *s = "example";    char *copy;    allocString( strlen(s), &copy );    strcpy( copy, s);    free (copy); }

Multi-dimensional arrays

Multi-dimensional arrays Can be created in few ways: 1. Automatically: int m[2][3]; // 2 rows, 3 columns continuous memory (divided to 2 blocks) access: m[row][col] = 0;

Automatic multi-dimensional arrays #define R 2 #define C 3 int m[R][C]; int* m_ptr= &(m[0][0]); for (int i=0; i<R*C; ++i) { printf(“%d\n”, *m_ptr++); }

Automatic multi-dimensional arrays int A[R][C]; A[0][0] A[0][1] … A[0][c-1] A[i][0] A[i][1] A[i][c-1] A[R-1][0] A[R-1][1] A[R-1][C-1] Like a matrix  Row-major ordering  A [0] [C-1] • • • A[0] A [i] [0] [C-1] • • • A[i] A [R-1] [0] [C-1] • • • A[R-1] •  •  • •  •  • A A+i*C*4 A+(R-1)*C*4 Starting address of A[i]

Semi-dynamic multi-dimensional arrays Define an array of pointers: int *pa[5]; // allocates memory for 5 pointers for (i=0; i<5; i++) {    pa[i] = (int*) malloc( 7*sizeof(int) );    // pa[i] now points to a memory for 7 ints }

Dynamic multi-dimensional arrays 3. Dynamically: int ** array; array = (int**) malloc( 5*sizeof(int*) ); for (i=0; i<5; i++) {    array[i] = malloc( 7*sizeof(int) ); }

Semi/Dynamic multi-dimensional arrays Memory not continuous Each pointer can be with different size Access: arr[ i ][ j ] Don’t forget to free all the memory: for (i=0; i<nrows; i++ ) {    free( array[i] ); } free( array ); // only for dynamic

Dynamic arrays – more efficient way int* A= (int*) malloc(R*C*sizeof(int)); 1-D array R=3 C=2  0,0 0,1 0,2 1,0 1,1 1,2 Access: A[ i*C + j ] // A [i][j] One access to memory vs. two in previous semi/dynamic representations. Easier (& more efficient) implementation of iterators But: Less readable code (can hide with macro or much better, inline functions)

Pointers to pointers to … We also have pointers to pointers to pointers, etc.: double ** mat1 = getMatrix(); double ** mat2 = getMatrix(); //allocate an array of matrices double *** matrices = (double***) malloc(n*sizeof(double**)); matrices[0] = mat1; matrices[1] = mat2;

Multi-dimensional arrays as arguments to functions int arr[5][7]; // 5 rows, 7 columns When sending ‘arr’ as an argument to a function, only the 1st index can be omitted: void func( int x[5][7] ) //ok void func( int x[][7] ) //ok void func( int x[][] ) //error (always) void func( int * x[] ) //something else void func( int ** x ) //something else

Why ?

Pointers to arrays (of size X): int foo (char arr[][20]); arr is a pointer to an array of 20 chars. Therefore: sizeof (arr) = sizeof (void*); sizeof (*arr) = 20*sizeof (char);

Pointers to arrays (of size X): Explicit declaration: char (*arr_2d)[20]; // arr_2d is a pointer // not initialized Using typedef: typdef char arr_2d_20[20]; arr_2d_20 *p_arr_2d; But: typdef char arr_2d[][]; // comp. error

Pointers to arrays (of size X): char (*arr)[5]; char *arr[5]; After initialization arr

Pointers to arrays (of size X): char (*arr)[5]; char *arr[5]; sizeof (arr) = sizeof(void*) sizeof (*arr) = 5*sizeof(char) sizeof (arr) = 5*sizeof (char*) = 5*sizeof (void*) sizeof (*arr) = sizeof (char*)= sizeof (void*)

Multi-dimensional arrays as arguments to functions

Multi-dimensional arrays as arguments to functions void foo( int matrix[ROWS_NUM][COLS_NUM] ) {

Multi-dimensional arrays as arguments to functions void foo( int matrix[ROWS_NUM][COLS_NUM] ) { What is really sent?

Multi-dimensional arrays as arguments to functions void foo( int (*matrix)[COLS_NUM] ) { pointer to an array of COLS_NUM ints!

Multi-dimensional arrays as arguments to functions void foo( int (*matrix)[COLS_NUM] ) { ... ... matrix[r][c]

Multi-dimensional arrays as arguments to functions void foo( int (*matrix)[COLS_NUM] ) { ... ... matrix[r][c] ... (*(matrix+r))[c]

Multi-dimensional arrays as arguments to functions void foo( int (*matrix)[COLS_NUM] ) { ... ... matrix[r][c] ... (*(matrix+r))[c] matrix is a pointer to int[COLS_NUM]. addition is done in this units. This is why COLS_NUM is needed!

Multi-dimensional arrays as arguments to functions void foo( int (*matrix)[COLS_NUM] ) { ... ... matrix[r][c] ... (*(matrix+r))[c] ... *((*(matrix+r)) + c)

Multi-dimensional arrays as arguments to functions void foo( int (*matrix)[COLS_NUM] ) { ... ... matrix[r][c] ... (*(matrix+r))[c] ... *((*(matrix+r)) + c) == *(matrix+r*COLS_NUM+c) The compiler is probably optimizing the internal computation to this.

Example of dynamic multidimensional array: argv, argc We want to pass parameters to the program running via the shell

argv, argc To pass command line arguments to our program we should use the following main declaration: main(int argc, char* argv[]) { ... Compare to main(String[] args) in java. Unlike java the first argument is the name of the program itself. char** argv char argv[][]

argv & argc: example $ prog1 –u danny –p 1234 argc == 5 argv[0] == “prog1” argv[1] == “-u” ... argv[4] == “1234” Always: argv[argc] == NULL (redundant since we are also given argc)