Programming. Pointers, Multi-dimensional Arrays and Memory Management
|
|
- Owen Cummings
- 6 years ago
- Views:
Transcription
1 Programming Pointers, Multi-dimensional Arrays and Memory Management
2 Summary } Computer Memory } Pointers } Declaration, assignment, arithmetic and operators } Casting and printing pointers } Relationship with arrays } Multidimensional arrays } 2D examples } Memory management } Malloc/calloc/realloc } Vectors of pointers 2
3 Computer Memory } The minimum addressable unit is a byte } Bytes are combined to make integers and floating point values } Memory addresses in computers are often 32 bits (or nowadays, 64-bits) long, e.g. 0x7ffffa8c (hexadecimal) int (21) float (18.2) 3 Memory addresses!
4 Physical and Virtual Memory } Physical memory: physical resources where data can be stored and accessed by the processing unit } Cache, RAM, hard disk, removable storage } Virtual memory: abstraction by OS, addressable space accessible by your code } How much virtual memory can you have? } Typically 2 GB for Windows, 3-4 GB for Linux } Virtual memory maps to different parts of physical memory } Usable parts of virtual memory: stack and heap } stack: memory space for declared variables } heap: memory space for dynamic memory 4
5 Pointers } A pointer is just a memory location } A memory location is simply an integer value that can be interpreted as an address in memory } Address can be used to access/modify a variable from anywhere } Extremely useful, especially for data structures } The contents at a particular memory location are just a collection of bits } You must tell the compiler how the bits should be interpreted } Is this... an int value?... a pointer to a memory address?... a series of char values? 0xfe4a10c5 5
6 Pointer Variables } A pointer variable is just a variable, that contains a value that can be interpreted as a memory address } An uninitialized int variable holds some arbitrary garbage value } An uninitialized pointer variable points to some arbitrary garbage address } What happens when an arbitrary address is followed? } Depends on the arbitrary memory address! } In case the address lies in memory not allocated by the program, a segmentation fault may occur char *pm; 6 pm (char *) Memory Address Address Variable Value 0x4520 m 181 0x4524 pm 0x4520 Pointer Value
7 Addressing Variables } Every variable residing in memory has an address! } Address of a variable of type t has type t* } Just like other variables, they must be declared before use } What doesn t have an address? } Register variables } Constants/literals/preprocessor defines } Expressions } How to find an address of a variable? } The & operator! } & operator means address of } Read it as at 7
8 Pointer Declaration and Initialization } Declaration: } int *pa; /* not initialized: points to a random location */ } Declaration and initialization: } int a = 2; /* a is an integer */ } int *pa = &a; /* pa is a pointer containing the address of a */ } Usage } scanf( %d, pa); /* Don t have to put & before */ } pa is a pointer variable that stores the address of an integer variable a pa 8
9 Printing Pointers int a = 21; int *pa = &a; printf("%d\n", a); printf("%x\n", a); printf("%x\n", &a); printf("%x\n", pa); printf("%d\n", *pa); printf("%x\n", &pa); Output bfee861c bfee861c 21 bfee8618 %x prints an hexadecimal value %p prints the pointer value Operators: & address of * dereference 9
10 Example Code: What is the Output? #include <stdio.h> Address Memory Name int main() { int a = 15, b = 38; int *c = &a; printf("%p : %d\n", &a, a); printf("%p : %d\n", &b,b); printf("%p : %p : %d\n", &c, c, *c); 0xeffffa94 0xeffffa90 0xeffffa8c 0xeffffa xeffffa a b c a a = 49; printf("%p : %d\n", &a, a); printf("%p : %d\n", &b,b); printf("%p : %p : %d\n", &c, c, *c); 0xeffffa90 0xeffffa8c 38 0xeffffa94 b c } c = &b; printf("%p : %d\n", &a, a); printf("%p : %d\n", &b,b); printf("%p : %p : %d\n", &c, c, *c); 0xeffffa94 0xeffffa90 0xeffffa8c xeffffa90 a b c 10
11 NULL Pointer Value } There is a special pointer value NULL, that means pointing to nothing. Same as value 0. char *m = NULL;... if (m) {... safe to follow the pointer... } } Here, m is used as a Boolean value } If m is false, aka 0, aka NULL, it is not pointing to anything } Otherwise, it is (presumably) pointing to a valid address } Note: It is up to the programmer to assign NULL values when necessary 11
12 Indirection Operator * } I have a pointer what to do? } Pointer allows to obtain the contents of an address } Dereferenced pointer is like any other variable char *m = dog ; char result = *m; printf ( %c, *m); d o g \0 } m is an address of a char } *m allows to obtain the content of that address } result assumes the value d (char *) m d result 12
13 Address Operator & } Instead of the contents, returns the address! char *m = dog ; char result = *m; d o g \0 char *pr = &result; char **ppm = &m; (char *) m d result } pr needs a value of type char * } points to a char } ppm needs a value of type char ** (char **) ppm (char *) pr } points to a pointer of char 13
14 Pointer Assignment I } The assignment operator (=) may be used to copy pointers of the same type } Assume the following declaration: } int i, j, *p, *q; } Example of pointer assignment: } p = &i; // p points to variable i } q = p; // q points to the same place as p p? i p? i q q 14
15 Pointer Assignment II } If p and q both point to i, we may change i by assigning a new value to either *p or *q: *p = 1; p 1 i *q = 2; q p 2 i q } Any number of pointer variables may point to the same variable
16 Pointer Assignment III } The following assignment statements are NOT the same: q = p; *q = *p; } The first statement is a pointer assignment } The second statements assigns the value of the data that is pointed-to by p to the data that is pointed-to by q
17 Pointer Arithmetic I } C allows pointer values to be incremented by integer values char *m = dog ; d o g NUL char result = *(m + 1); } m is an address of a char } (m + 1) allows to obtain the next address } *(m + 1) allows to obtain the contents of the address of the next char } result gets the value o (char *) m o result 17
18 Pointer Arithmetic II } A slightly more complex example: char *m = dog ; d o g NUL char result = *++m; } m is an address of a char (char *) } ++m changes m to the address one byte higher } Careful! we have lost our pointer to the beginning of the array!!! } *++m allows to obtain the contents of that location } result gets the value o m o result 18
19 Pointer Arithmetic III } For pointers, only addition and subtraction are allowed } Other arithmetic operations don t make much sense } Pointers arithmetic depend on the type of data that the pointer has } Different data types have different sizes int a[2] = {17, 42}; int *m = a; int result = *++m; 17 (int) 42 (int) 19 (int *) m 42 (int) result
20 Pointer Arithmetic: Examples int list[] = {1, 2, 3, 4}; int *p = list; /* same as p = &list[0] */ printf( %x,p); /* prints ffe2de0c */ p = p + 1; /* p increases by 4 */ printf( %x,p); /* prints ffe2de10 */ double list2[] = {1.0, 2.0, 3.0}; double *p = list2; /* same as p = &list2[0] */ printf( %x,p); /* prints ffe2de0c */ p = p + 1; /* P increases by 8 bytes */ printf( %x,p); /* prints ffe2de14 */ 20
21 Casting Pointers } Can explicitly cast any pointer type to any other pointer type ppi = (double *)pn; /* pn originally of type ( int *) */ } Dereferenced pointer has new type, regardless of real type of data } Implicit cast to/from void * also possible } May cause segmentation faults and other difficult-to-identify errors 21
22 Arrays and Pointers Share Similarities } Name of the array is a pointer to the first element of an array } &aarray[0] is the same as aarray, points to the 1 st array element } After assigning the address of the first element of aarray, it is possible to access other elements of aarray: int aarray[100] = {0}; parray = &aarray[0]; *(parray + 1) = 20 // assign 20 to 2nd element of aarray *(parray + 4) = 30; // assign 30 to 5th element of aarray parray = &parray[3]; *(parray + 1) = 50; // assign 50 to 5th element of aarray 22
23 Pointer and [] } Any pointer to a block of memory can use the [] syntax, even if it is not declared as an array! } int *v; and int v[]; are the same thing int *p, int list[]={1,2,3,4}; p = list; // prints 3 printf( %d\n, p[2]); // two equivalent statements printf( %d, list[2]); printf( %d,*(list+2)); P List
24 Pointers and Arrays: Example #define N_VALUES 5 float values[n_values]; (float []) values &values[0] &values [N_VALUES] (float) (float) (float) (float) (float) 0 0 (done!) vp (float *) float *vp; for ( vp = &values[0]; vp < &values[n_values]; ) *vp++ = 0;
25 Example: strcpy string copy char *strcpy(char *dest, const char *src) } src points to a sequence of char values that must be copied to dest, terminated by \0 } dest points to a portion of memory large enough to hold the copied chars } strcpy copies the char values of src to the memory pointed to by dest } strcpy also gives dest as a return value 25
26 Example: strcpy string copy char *strcpy(char *dest, const char *src) { } const char *p; char *q; for(p = src, q = dest; *p!= '\0'; p++, q++) *q = *p; *q = '\0'; return dest; (char *) src d o g NUL p (char *) (char *) q (char *) dest d o g NUL 26
27 Review: Pass by Value vs Pass by Reference } How to return more than one value? Pass by Reference! } Must use pointers in the calling function } The address of the value to be modified is passed as argument } & operator must be used int x, y; x = 5; y = sum2(x); int x,y; x = 5; y = 10; sumdiv(&x,&y); printf( %d %d\n,x,y); int sum2(int t) { return (t + t); } &x and &t are different x value is copied to t void sumdiv(int *_x, int *_y) { *_x = *_x + *_y; *_y = *_x / *_y; } _x and &x are equal _y and &y are equal 27
28 2D Arrays } Declaration: } int mymatrix[row_size][col_size]; } Declaration and Initialization: } int mymatrix[4][4] = { {1,2,3,4}, {5,6,7,8}, {9,10,11,12}, {13,14,15,16} }; Column Row mymatrix[0][1] mymatrix[2][3] 12 28
29 Physically in One Memory Block } int mymatrix[2][4] = { {1,2,3,4},{5,6,7,8} }; } mymatrix: pointer to the first element of the 2D array (position [0][0]) } mymatrix[0]: pointer to the first row of the 2D array (it is a vector) } mymatrix[1]: pointer to the second row of the 2D array } &mymatrix[1] is the address of element mymatrix[1][0] } &mymatrix[0][0] is the address of 1 st element (same as mymatrix) ffe2de0c ffe2de10 ffe2de14 ffe2de18 ffe2de1c ffe2de20 ffe2de24 ffe2de row 1 row 2 Array elements are stored in row major order Row 1 first, followed by row2, row3, and so on 29
30 Functions of Multi-dimensional Arrays #define ROWS 3 #define COLS 5 int table[rows][cols]; // some processing... display(table); Arrays are always passed by reference After all, table is a pointer! void display( int x[][cols] ) To pass a multi-dimensional { array, the first array size does for (int i=0; i < ROWS; i++) not have to be specified but { the second (and any next) for (int j=0; j < COLS; j++ ) dimensions must be given! { printf( x[%d][%d]: %d\n", i, j, x[i][j]); } printf("\n"); } printf("\n"); } 30
31 Dynamic Memory } Vectors: Size must be known before compilation } Example: int vect[200]; int n = 300; int vect[n]; //not possible to do! } How to create vectors that are dynamic? } Must use pointers } int *vect = (int *) calloc(n, sizeof(int)); 31
32 Memory Management: Stack Allocated } When a function is called, memory is allocated for all of its parameters and local variables } Each active function call has memory on the stack (with the current function call on top) } When a function call terminates, the memory is deallocated ( freed up ) } Ex: main() calls f(), f() calls g() g() recursively calls g() g() g() f() main() 32
33 Memory Management: Heap Allocated } This is used for persistent data, that must survive beyond the lifetime of a function call } Global variables } Dynamically allocated memory C statements can create new heap data } Heap memory is allocated in a more complex way than stack memory } Like stack-allocated memory, the underlying system determines where the new memory comes from 33
34 Allocating Heap Memory void *malloc(size_t size); void *calloc(size_t num_elements, size_t element_size); } malloc: allocates a block of size bytes } calloc: allocates a block of num_elements * element_size bytes } Both functions return a pointer to the block } Note: void* denotes a generic pointer type } Both functions return NULL if unable to allocate memory } It is needed to cast the return value of malloc/calloc: } char *p = (char *) malloc(buffer_size); 34
35 Reallocating Heap Memory void *realloc(void *ptr, size_t new_size); } Given a previously allocated block starting at ptr } Change the block size to new_size } Return pointer to resized block } If block size is increased, contents of old block may be copied to a completely different region } In this case, the pointer returned will be different from the ptr argument, and ptr will no longer point to a valid memory region } If ptr is NULL, realloc is identical to malloc 35
36 Deallocating Heap Memory void free(void *pointer); } Given a pointer to previously allocated memory } Put the block back in the heap of unallocated memory in order to be reused } Note: easy to forget to free memory when it is no longer needed... } This is the source of the notorious memory leak problem } Difficult to trace the program may execute correctly for some time, until suddenly there is no more memory! 36
37 Safer Malloc } If there is no memory available, call to malloc might fail! } Easy to forget to check for this! void *alloc(size_t size) { void *new_mem; new_mem = malloc(size); if (new_mem == NULL) exit(1); return new_mem; } 37
38 Common Memory Errors } Using memory that was not initialized } Uninitialized memory read or copy } Attempts to read/write contents of a NULL pointer } Very common error } Using memory that was not allocated in your program } Pointer arithmetic may lead to memory not allocated by you } Invalid pointer read/write due to memory management (e.g. realloc) } Using more memory than it was allocated } Access of memory that has been freed earlier } Using memory that it was allocated in the stack, but already freed } Reading an array out of its limits (bounds) } Memory leak: discarding a pointer without freeing memory! 38
39 Pointer of Pointers } Address stored by pointer is also data in memory } The location of an address stored in memory can be addressed using a pointer to that pointer } int n = 4; } int *pn = &n; } int **ppn = &pn; } Many uses: } Image storage } Vectors of strings 39
40 Pointer Arrays } Pointer array array of pointers } int arr [20]; // an array of pointers to integers } char arr [10]; // an array of pointers to chars } Array of strings: each string stored as a pointer to an array of chars } Each string may be of different length char str1[] = "hello"; / length = 6 / char str2[] = "goodbye"; / length = 8 / char str3[] = "ciao"; / length = 5 / char strarray[] = {str1, str2, str3}; } Note: strarray contains only pointers, not the characters themselves! 40
41 Pointer Arrays: Example #include <stdio.h> int main(void) { char *arr[3]; char *p1 = Delhi"; char *p2 = Kolkata"; char *p3 = "India"; arr[0] = p1; arr[1] = p2; arr[2] = p3; printf("\n p1 = [%s] \n",p1); printf("\n p2 = [%s] \n",p2); printf("\n p3 = [%s] \n",p3); printf("\n arr[0] = [%s] \n",arr[0]); printf("\n arr[1] = [%s] \n",arr[1]); printf("\n arr[2] = [%s] \n",arr[2]); } 41 return 0;
42 Dynamic Pointer Arrays #include <stdlib.h> int **array; array = malloc(nrows*sizeof(int *)); if(array == NULL) { fprintf(stderr, "out of memory\n"); exit(-1); } for(i = 0; i < nrows; i++) { array[i] = malloc(ncolumns*sizeof(int)); if(array[i] == NULL) { fprintf(stderr, "out of memory\n"); exit(-1); } } } Straightforward to call malloc to allocate a block of memory with a size computed at runtime } Can the same sort of thing being used to create multidimensional arrays? } Must use pointers of pointers! 42
43 To Review } Marques de Sá } Capítulo 5.6 e Capítulo 9.1 } Damas } Capítulo 8 } Capítulo 12 } Kernighan and Ritchie } Chapter 5 43
Dynamic memory allocation
Dynamic memory allocation outline Memory allocation functions Array allocation Matrix allocation Examples Memory allocation functions (#include ) malloc() Allocates a specified number of bytes
More informationCS 11 C track: lecture 5
CS 11 C track: lecture 5 Last week: pointers This week: Pointer arithmetic Arrays and pointers Dynamic memory allocation The stack and the heap Pointers (from last week) Address: location where data stored
More informationDynamic Allocation in C
Dynamic Allocation in C C Pointers and Arrays 1 The previous examples involved only targets that were declared as local variables. For serious development, we must also be able to create variables dynamically,
More informationFundamental of Programming (C)
Borrowed from lecturer notes by Omid Jafarinezhad Fundamental of Programming (C) Lecturer: Vahid Khodabakhshi Lecture 9 Pointer Department of Computer Engineering 1/46 Outline Defining and using Pointers
More informationJagannath Institute of Management Sciences Lajpat Nagar. BCA II Sem. C Programming
Jagannath Institute of Management Sciences Lajpat Nagar BCA II Sem C Programming UNIT I Pointers: Introduction to Pointers, Pointer Notation,Decalaration and Initialization, Accessing variable through
More informationIn Java we have the keyword null, which is the value of an uninitialized reference type
+ More on Pointers + Null pointers In Java we have the keyword null, which is the value of an uninitialized reference type In C we sometimes use NULL, but its just a macro for the integer 0 Pointers are
More informationArrays and Pointers. CSE 2031 Fall November 11, 2013
Arrays and Pointers CSE 2031 Fall 2013 November 11, 2013 1 Arrays l Grouping of data of the same type. l Loops commonly used for manipulation. l Programmers set array sizes explicitly. 2 Arrays: Example
More informationDynamic memory allocation (malloc)
1 Plan for today Quick review of previous lecture Array of pointers Command line arguments Dynamic memory allocation (malloc) Structures (Ch 6) Input and Output (Ch 7) 1 Pointers K&R Ch 5 Basics: Declaration
More informationArrays and Pointers. Arrays. Arrays: Example. Arrays: Definition and Access. Arrays Stored in Memory. Initialization. EECS 2031 Fall 2014.
Arrays Arrays and Pointers l Grouping of data of the same type. l Loops commonly used for manipulation. l Programmers set array sizes explicitly. EECS 2031 Fall 2014 November 11, 2013 1 2 Arrays: Example
More informationDynamic Allocation in C
Dynamic Allocation in C 1 The previous examples involved only targets that were declared as local variables. For serious development, we must also be able to create variables dynamically, as the program
More informationMemory Management. CSC215 Lecture
Memory Management CSC215 Lecture Outline Static vs Dynamic Allocation Dynamic allocation functions malloc, realloc, calloc, free Implementation Common errors Static Allocation Allocation of memory at compile-time
More informationLecture 8 Dynamic Memory Allocation
Lecture 8 Dynamic Memory Allocation CS240 1 Memory Computer programs manipulate an abstraction of the computer s memory subsystem Memory: on the hardware side 3 @ http://computer.howstuffworks.com/computer-memory.htm/printable
More informationDynamic Memory Allocation (and Multi-Dimensional Arrays)
Dynamic Memory Allocation (and Multi-Dimensional Arrays) Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2 nd edition, by Kernighan
More informationClass Information ANNOUCEMENTS
Class Information ANNOUCEMENTS Third homework due TODAY at 11:59pm. Extension? First project has been posted, due Monday October 23, 11:59pm. Midterm exam: Friday, October 27, in class. Don t forget to
More informationComputer Programming Unit 3
POINTERS INTRODUCTION Pointers are important in c-language. Some tasks are performed more easily with pointers such as dynamic memory allocation, cannot be performed without using pointers. So it s very
More information[0569] p 0318 garbage
A Pointer is a variable which contains the address of another variable. Declaration syntax: Pointer_type *pointer_name; This declaration will create a pointer of the pointer_name which will point to the
More informationPOINTER AND ARRAY SUNU WIBIRAMA
POINTER AND ARRAY SUNU WIBIRAMA Presentation Outline Basic Pointer Arrays Dynamic Memory Allocation Basic Pointer 3 Pointers A pointer is a reference to another variable (memory location) in a program
More informationC Pointers. Abdelghani Bellaachia, CSCI 1121 Page: 1
C Pointers 1. Objective... 2 2. Introduction... 2 3. Pointer Variable Declarations and Initialization... 3 4. Reference operator (&) and Dereference operator (*) 6 5. Relation between Arrays and Pointers...
More informationPointers (part 1) What are pointers? EECS We have seen pointers before. scanf( %f, &inches );! 25 September 2017
Pointers (part 1) EECS 2031 25 September 2017 1 What are pointers? We have seen pointers before. scanf( %f, &inches );! 2 1 Example char c; c = getchar(); printf( %c, c); char c; char *p; c = getchar();
More informationDynamic Memory Allocation
Dynamic Memory Allocation The process of allocating memory at run time is known as dynamic memory allocation. C does not Inherently have this facility, there are four library routines known as memory management
More informationC: Pointers, Arrays, and strings. Department of Computer Science College of Engineering Boise State University. August 25, /36
Department of Computer Science College of Engineering Boise State University August 25, 2017 1/36 Pointers and Arrays A pointer is a variable that stores the address of another variable. Pointers are similar
More informationAnnouncements. assign0 due tonight. Labs start this week. No late submissions. Very helpful for assign1
Announcements assign due tonight No late submissions Labs start this week Very helpful for assign1 Goals for Today Pointer operators Allocating memory in the heap malloc and free Arrays and pointer arithmetic
More informationo Code, executable, and process o Main memory vs. virtual memory
Goals for Today s Lecture Memory Allocation Prof. David August COS 217 Behind the scenes of running a program o Code, executable, and process o Main memory vs. virtual memory Memory layout for UNIX processes,
More informationCS 31: Intro to Systems Pointers and Memory. Kevin Webb Swarthmore College October 2, 2018
CS 31: Intro to Systems Pointers and Memory Kevin Webb Swarthmore College October 2, 2018 Overview How to reference the location of a variable in memory Where variables are placed in memory How to make
More informationCS201- Introduction to Programming Current Quizzes
CS201- Introduction to Programming Current Quizzes Q.1 char name [] = Hello World ; In the above statement, a memory of characters will be allocated 13 11 12 (Ans) Q.2 A function is a block of statements
More informationadvanced data types (2) typedef. today advanced data types (3) enum. mon 23 sep 2002 defining your own types using typedef
today advanced data types (1) typedef. mon 23 sep 2002 homework #1 due today homework #2 out today quiz #1 next class 30-45 minutes long one page of notes topics: C advanced data types dynamic memory allocation
More informationMemory Allocation in C C Programming and Software Tools. N.C. State Department of Computer Science
Memory Allocation in C C Programming and Software Tools N.C. State Department of Computer Science The Easy Way Java (JVM) automatically allocates and reclaims memory for you, e.g... Removed object is implicitly
More informationArrays and Memory Management
Arrays and Memory Management 1 Pointing to Different Size Objects Modern machines are byte-addressable Hardware s memory composed of 8-bit storage cells, each has a unique address A C pointer is just abstracted
More informationDynamic Allocation of Memory Space
C Programming 1 Dynamic Allocation of Memory Space C Programming 2 Run-Time Allocation of Space The volume of data may not be known before the run-time. It provides flexibility in building data structures.
More informationC: Pointers. C: Pointers. Department of Computer Science College of Engineering Boise State University. September 11, /21
Department of Computer Science College of Engineering Boise State University September 11, 2017 1/21 Pointers A pointer is a variable that stores the address of another variable. Pointers are similar to
More informationChapter 14. Dynamic Data Structures. Instructor: Öğr. Gör. Okan Vardarlı. Copyright 2004 Pearson Addison-Wesley. All rights reserved.
Chapter 14 Dynamic Data Structures Instructor: Öğr. Gör. Okan Vardarlı Copyright 2004 Pearson Addison-Wesley. All rights reserved. 12-1 Dynamic Data Structure Usually, so far, the arrays and strings we
More informationQuick review pointer basics (KR ch )
1 Plan for today Quick review pointer basics (KR ch5.1 5.5) Related questions in midterm Continue on pointers (KR 5.6 -- ) Array of pointers Command line arguments Dynamic memory allocation (malloc) 1
More informationPointers, Dynamic Data, and Reference Types
Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation The new operator The delete operator Dynamic Memory Allocation for Arrays 1 C++ Data Types simple
More informationCS107 Handout 08 Spring 2007 April 9, 2007 The Ins and Outs of C Arrays
CS107 Handout 08 Spring 2007 April 9, 2007 The Ins and Outs of C Arrays C Arrays This handout was written by Nick Parlante and Julie Zelenski. As you recall, a C array is formed by laying out all the elements
More informationReminder of midterm 1. Next Thursday, Feb. 14, in class Look at Piazza announcement for rules and preparations
Reminder of midterm 1 Next Thursday, Feb. 14, in class Look at Piazza announcement for rules and preparations A New Example to see effect of E++ (better than the one in previous lecture) Purpose of showing
More informationCSCI 171 Chapter Outlines
Contents CSCI 171 Chapter 1 Overview... 2 CSCI 171 Chapter 2 Programming Components... 3 CSCI 171 Chapter 3 (Sections 1 4) Selection Structures... 5 CSCI 171 Chapter 3 (Sections 5 & 6) Iteration Structures
More informationChapter 2 (Dynamic variable (i.e. pointer), Static variable)
Chapter 2 (Dynamic variable (i.e. pointer), Static variable) August_04 A2. Identify and explain the error in the program below. [4] #include int *pptr; void fun1() { int num; num=25; pptr= #
More informationContent. In this chapter, you will learn:
ARRAYS & HEAP Content In this chapter, you will learn: To introduce the array data structure To understand the use of arrays To understand how to define an array, initialize an array and refer to individual
More informationArrays and Pointers (part 1)
Arrays and Pointers (part 1) CSE 2031 Fall 2012 Arrays Grouping of data of the same type. Loops commonly used for manipulation. Programmers set array sizes explicitly. Arrays: Example Syntax type name[size];
More informationFall 2018 Discussion 2: September 3, 2018
CS 61C C Basics Fall 2018 Discussion 2: September 3, 2018 1 C C is syntactically similar to Java, but there are a few key differences: 1. C is function-oriented, not object-oriented; there are no objects.
More informationDynamic Memory. Dynamic Memory Allocation Strings. September 18, 2017 Hassan Khosravi / Geoffrey Tien 1
Dynamic Memory Dynamic Memory Allocation Strings September 18, 2017 Hassan Khosravi / Geoffrey Tien 1 Pointer arithmetic If we know the address of the first element of an array, we can compute the addresses
More informationMemory Management I. two kinds of memory: stack and heap
Memory Management I two kinds of memory: stack and heap stack memory: essentially all non-pointer (why not pointers? there s a caveat) variables and pre-declared arrays of fixed (i.e. fixed before compilation)
More informationLab 3. Pointers Programming Lab (Using C) XU Silei
Lab 3. Pointers Programming Lab (Using C) XU Silei slxu@cse.cuhk.edu.hk Outline What is Pointer Memory Address & Pointers How to use Pointers Pointers Assignments Call-by-Value & Call-by-Address Functions
More informationCS 61C: Great Ideas in Computer Architecture. C Arrays, Strings, More Pointers
CS 61C: Great Ideas in Computer Architecture C Arrays, Strings, More Pointers Instructor: Justin Hsia 6/20/2012 Summer 2012 Lecture #3 1 Review of Last Lecture C Basics Variables, Functions, Flow Control,
More informationToday s lecture. Pointers/arrays. Stack versus heap allocation CULTURE FACT: IN CODE, IT S NOT CONSIDERED RUDE TO POINT.
Pointers/arrays Mechanics, syntax Underlying memory model Array indexing == pointer arithmetic As parameters Stack versus heap allocation Stack declaration, scope, lifetime Heap allocation/deallocation
More informationC Programming & Memory
Signals, Instruments, and Systems W3 C Programming & Memory Management in C Outline Week 2: main concepts of C introduced Today: consolidation and refinement of your understanding of C Further details
More informationPOINTER & REFERENCE VARIABLES
Lecture 9 POINTER & REFERENCE VARIABLES Declaring data pointer variables Assignment operations with pointers Referring objects using pointer variables Generic pointers Operations with pointer variables
More informationMemory Allocation. General Questions
General Questions 1 Memory Allocation 1. Which header file should be included to use functions like malloc() and calloc()? A. memory.h B. stdlib.h C. string.h D. dos.h 2. What function should be used to
More informationArrays and Pointers (part 1)
Arrays and Pointers (part 1) CSE 2031 Fall 2010 17 October 2010 1 Arrays Grouping of data of the same type. Loops commonly used for manipulation. Programmers set array sizes explicitly. 2 1 Arrays: Example
More informationArrays and Pointers in C. Alan L. Cox
Arrays and Pointers in C Alan L. Cox alc@rice.edu Objectives Be able to use arrays, pointers, and strings in C programs Be able to explain the representation of these data types at the machine level, including
More informationAgenda. Peer Instruction Question 1. Peer Instruction Answer 1. Peer Instruction Question 2 6/22/2011
CS 61C: Great Ideas in Computer Architecture (Machine Structures) Introduction to C (Part II) Instructors: Randy H. Katz David A. Patterson http://inst.eecs.berkeley.edu/~cs61c/sp11 Spring 2011 -- Lecture
More informationIntermediate Programming, Spring 2017*
600.120 Intermediate Programming, Spring 2017* Misha Kazhdan *Much of the code in these examples is not commented because it would otherwise not fit on the slides. This is bad coding practice in general
More informationLecture 14. No in-class files today. Homework 7 (due on Wednesday) and Project 3 (due in 10 days) posted. Questions?
Lecture 14 No in-class files today. Homework 7 (due on Wednesday) and Project 3 (due in 10 days) posted. Questions? Friday, February 11 CS 215 Fundamentals of Programming II - Lecture 14 1 Outline Static
More informationCS 261 Fall C Introduction. Variables, Memory Model, Pointers, and Debugging. Mike Lam, Professor
CS 261 Fall 2017 Mike Lam, Professor C Introduction Variables, Memory Model, Pointers, and Debugging The C Language Systems language originally developed for Unix Imperative, compiled language with static
More informationCS 31: Intro to Systems Pointers and Memory. Martin Gagne Swarthmore College February 16, 2016
CS 31: Intro to Systems Pointers and Memory Martin Gagne Swarthmore College February 16, 2016 So we declared a pointer How do we make it point to something? 1. Assign it the address of an existing variable
More informationWhy Pointers. Pointers. Pointer Declaration. Two Pointer Operators. What Are Pointers? Memory address POINTERVariable Contents ...
Why Pointers Pointers They provide the means by which functions can modify arguments in the calling function. They support dynamic memory allocation. They provide support for dynamic data structures, such
More informationUnderstanding Pointers
Division of Mathematics and Computer Science Maryville College Pointers and Addresses Memory is organized into a big array. Every data item occupies one or more cells. A pointer stores an address. A pointer
More informationC Structures & Dynamic Memory Management
C Structures & Dynamic Memory Management Goals of this Lecture Help you learn about: Structures and unions Dynamic memory management Note: Will be covered in precepts as well We look at them in more detail
More informationSystems Programming and Computer Architecture ( )
Systems Group Department of Computer Science ETH Zürich Systems Programming and Computer Architecture (252-0061-00) Timothy Roscoe Herbstsemester 2016 1 4: Pointers Computer Architecture and Systems Programming
More informationMemory (Stack and Heap)
Memory (Stack and Heap) Praktikum C-Programmierung Nathanael Hübbe, Eugen Betke, Michael Kuhn, Jakob Lüttgau, Jannek Squar Wissenschaftliches Rechnen Fachbereich Informatik Universität Hamburg 2018-12-03
More informationCSCI-243 Exam 1 Review February 22, 2015 Presented by the RIT Computer Science Community
CSCI-243 Exam 1 Review February 22, 2015 Presented by the RIT Computer Science Community http://csc.cs.rit.edu History and Evolution of Programming Languages 1. Explain the relationship between machine
More informationArrays, Pointers and Memory Management
Arrays, Pointers and Memory Management EECS 2031 Summer 2014 Przemyslaw Pawluk May 20, 2014 Answer to the question from last week strct->field Returns the value of field in the structure pointed to by
More informationKurt Schmidt. October 30, 2018
to Structs Dept. of Computer Science, Drexel University October 30, 2018 Array Objectives to Structs Intended audience: Student who has working knowledge of Python To gain some experience with a statically-typed
More informationAPS105. Malloc and 2D Arrays. Textbook Chapters 6.4, Datatype Size
APS105 Malloc and 2D Arrays Textbook Chapters 6.4, 10.2 Datatype Size Datatypes have varying size: char: 1B int: 4B double: 8B int sizeof(): a builtin function that returns size of a type int x =
More informationch = argv[i][++j]; /* why does ++j but j++ does not? */
CMPS 12M Introduction to Data Structures Lab Lab Assignment 4 The purpose of this lab assignment is to get more practice programming in C, including the character functions in the library ctype.h, and
More informationPointers, Arrays, Memory: AKA the cause of those Segfaults
Computer Science 61C Spring 2018 Wawrzynek and Weaver Pointers, Arrays, Memory: AKA the cause of those F@#)(#@*( Segfaults 1 Agenda Computer Science 61C Spring 2018 Pointers Arrays in C Memory Allocation
More informationExercise 3 / Ch.7. Given the following array, write code to initialize all the elements to 0: int ed[100]; Hint: It can be done two different ways!
Exercise 3 / Ch.7 Given the following array, write code to initialize all the elements to 0: int ed[100]; Hint: It can be done two different ways! Exercise 3 / Ch.8 Given the following array, write code
More informationCS 61c: Great Ideas in Computer Architecture
Arrays, Strings, and Some More Pointers June 24, 2014 Review of Last Lecture C Basics Variables, functioss, control flow, types, structs Only 0 and NULL evaluate to false Pointers hold addresses Address
More informationPointers, Arrays, and Strings. CS449 Spring 2016
Pointers, Arrays, and Strings CS449 Spring 2016 Pointers Pointers are important. Pointers are fun! Pointers Every variable in your program has a memory location. This location can be accessed using & operator.
More informationC for Java Programmers 1. Last Week. Overview of the differences between C and Java. The C language (keywords, types, functies, etc.
C for Java Programmers 1 Last Week Very short history of C Overview of the differences between C and Java The C language (keywords, types, functies, etc.) Compiling (preprocessor, compiler, linker) C for
More informationThe output: The address of i is 0xbf85416c. The address of main is 0x80483e4. arrays.c. 1 #include <stdio.h> 3 int main(int argc, char **argv) 4 {
Memory A bit is a binary digit, either 0 or 1. A byte is eight bits, and can thus represent 256 unique values, such as 00000000 and 10010110. Computer scientists often think in terms of hexadecimal, rather
More informationMPATE-GE 2618: C Programming for Music Technology. Unit 5.1
MPATE-GE 2618: C Programming for Music Technology Unit 5.1 Review: automatic vs. static variables Variables declared and passed to functions are automatic variables. As soon as you leave the function,
More informationWeek 9 Part 1. Kyle Dewey. Tuesday, August 28, 12
Week 9 Part 1 Kyle Dewey Overview Dynamic allocation continued Heap versus stack Memory-related bugs Exam #2 Dynamic Allocation Recall... Dynamic memory allocation allows us to request memory on the fly
More informationCSC 1600 Memory Layout for Unix Processes"
CSC 16 Memory Layout for Unix Processes" 1 Lecture Goals" Behind the scenes of running a program" Code, executable, and process" Memory layout for UNIX processes, and relationship to C" : code and constant
More informationArrays. Returning arrays Pointers Dynamic arrays Smart pointers Vectors
Arrays Returning arrays Pointers Dynamic arrays Smart pointers Vectors To declare an array specify the type, its name, and its size in []s int arr1[10]; //or int arr2[] = {1,2,3,4,5,6,7,8}; arr2 has 8
More informationSystems Programming and Computer Architecture ( )
Systems Group Department of Computer Science ETH Zürich Systems Programming and Computer Architecture (252-0061-00) Timothy Roscoe Herbstsemester 2016 AS 2016 Dynamic Memory Allocation 1 5: Dynamic memory
More informationDynamic Data Structures. CSCI 112: Programming in C
Dynamic Data Structures CSCI 112: Programming in C 1 It s all about flexibility In the programs we ve made so far, the compiler knows at compile time exactly how much memory to allocate for each variable
More informationhttps://lambda.mines.edu A pointer is a value that indicates location in memory. When we change the location the pointer points to, we say we assign the pointer a value. When we look at the data the pointer
More informationHigh Performance Programming Programming in C part 1
High Performance Programming Programming in C part 1 Anastasia Kruchinina Uppsala University, Sweden April 18, 2017 HPP 1 / 53 C is designed on a way to provide a full control of the computer. C is the
More informationQuiz 0 Review Session. October 13th, 2014
Quiz 0 Review Session October 13th, 2014 Topics (non-exhaustive) Binary. ASCII. Algorithms. Pseudocode. Source code. Compiler. Object code. Scratch. Statements. Boolean expressions. Conditions. Loops.
More informationPointers. Part VI. 1) Introduction. 2) Declaring Pointer Variables. 3) Using Pointers. 4) Pointer Arithmetic. 5) Pointers and Arrays
EE105: Software Engineering II Part 6 Pointers page 1 of 19 Part VI Pointers 1) Introduction 2) Declaring Pointer Variables 3) Using Pointers 4) Pointer Arithmetic 5) Pointers and Arrays 6) Pointers and
More informationC Introduction. Comparison w/ Java, Memory Model, and Pointers
CS 261 Fall 2018 Mike Lam, Professor C Introduction Comparison w/ Java, Memory Model, and Pointers Please go to socrative.com on your phone or laptop, choose student login and join room LAMJMU The C Language
More informationEM108 Software Development for Engineers
EE108 Section 6 Pointers page 1 of 20 EM108 Software Development for Engineers Section 6 - Pointers 1) Introduction 2) Declaring Pointer Variables 3) Using Pointers 4) Pointer Arithmetic 5) Pointers and
More informationCS 137 Part 5. Pointers, Arrays, Malloc, Variable Sized Arrays, Vectors. October 25th, 2017
CS 137 Part 5 Pointers, Arrays, Malloc, Variable Sized Arrays, Vectors October 25th, 2017 Exam Wrapper Silently answer the following questions on paper (for yourself) Do you think that the problems on
More informationArrays. Example: Run the below program, it will crash in Windows (TurboC Compiler)
1 Arrays General Questions 1. What will happen if in a C program you assign a value to an array element whose subscript exceeds the size of array? A. The element will be set to 0. B. The compiler would
More informationProcedural programming with C
Procedural programming with C Dr. C. Constantinides Department of Computer Science and Software Engineering Concordia University Montreal, Canada August 11, 2016 1 / 77 Functions Similarly to its mathematical
More informationCMSC 341 Lecture 2 Dynamic Memory and Pointers
CMSC 341 Lecture 2 Dynamic Memory and Pointers Park Sects. 01 & 02 Based on earlier course slides at UMBC Today s Topics Stack vs Heap Allocating and freeing memory new and delete Memory Leaks Valgrind
More informationPROGRAMMAZIONE I A.A. 2017/2018
PROGRAMMAZIONE I A.A. 2017/2018 A pointer is a variable whose value is the address of another variable, i.e., direct address of the memory location. DECLARING POINTERS POINTERS A pointer represents both
More informationSignals, Instruments, and Systems W3. C Programming & Memory Management in C
Signals, Instruments, and Systems W3 C Programming & Memory Management in C 1 Remarks 2 Indentation, indentation, indentation, Indentation and spacing helps you and others (= TAs) read your code. It has
More informationCS61, Fall 2012 Section 2 Notes
CS61, Fall 2012 Section 2 Notes (Week of 9/24-9/28) 0. Get source code for section [optional] 1: Variable Duration 2: Memory Errors Common Errors with memory and pointers Valgrind + GDB Common Memory Errors
More informationC Language Part 1 Digital Computer Concept and Practice Copyright 2012 by Jaejin Lee
C Language Part 1 (Minor modifications by the instructor) References C for Python Programmers, by Carl Burch, 2011. http://www.toves.org/books/cpy/ The C Programming Language. 2nd ed., Kernighan, Brian,
More informationDynamic memory. EECS 211 Winter 2019
Dynamic memory EECS 211 Winter 2019 2 Initial code setup $ cd eecs211 $ curl $URL211/lec/06dynamic.tgz tar zx $ cd 06dynamic 3 Oops! I made a mistake. In C, the declaration struct circle read_circle();
More informationProcesses. Johan Montelius KTH
Processes Johan Montelius KTH 2017 1 / 47 A process What is a process?... a computation a program i.e. a sequence of operations a set of data structures a set of registers means to interact with other
More informationLecture07: Strings, Variable Scope, Memory Model 4/8/2013
Lecture07: Strings, Variable Scope, Memory Model 4/8/2013 Slides modified from Yin Lou, Cornell CS2022: Introduction to C 1 Outline Review pointers New: Strings New: Variable Scope (global vs. local variables)
More informationArrays Arrays and pointers Loops and performance Array comparison Strings. John Edgar 2
CMPT 125 Arrays Arrays and pointers Loops and performance Array comparison Strings John Edgar 2 Python a sequence of data access elements with [index] index from [0] to [len-1] dynamic length heterogeneous
More informationHigh-performance computing and programming Intro to C on Unix/Linux. Uppsala universitet
High-performance computing and programming Intro to C on Unix/Linux IT Uppsala universitet What is C? An old imperative language that remains rooted close to the hardware C is relatively small and easy
More informationCMPS 105 Systems Programming. Prof. Darrell Long E2.371
+ CMPS 105 Systems Programming Prof. Darrell Long E2.371 darrell@ucsc.edu + Chapter 7: The Environment of a UNIX process + Introduction + The main() fuction n int main(int argc, char* argv[]); n argc =
More informationTopics so far. Review. scanf/fscanf. How data is read 1/20/2011. All code handin sare at /afs/andrew/course/15/123/handin
15-123 Effective Programming in C and Unix Announcements SL2 is due Thursday 1/20 midnight Complete the Academic Honesty Form in class All code downloads are from /afs/andrew/course/15/123/download All
More informationA process. the stack
A process Processes Johan Montelius What is a process?... a computation KTH 2017 a program i.e. a sequence of operations a set of data structures a set of registers means to interact with other processes
More informationCSC209H Lecture 3. Dan Zingaro. January 21, 2015
CSC209H Lecture 3 Dan Zingaro January 21, 2015 Streams (King 22.1) Stream: source of input or destination for output We access a stream through a file pointer (FILE *) Three streams are available without
More information