CSCI206 - Computer Organization & Programming

Slides:



Advertisements
Similar presentations
Dynamic Memory Allocation in C.  What is Memory What is Memory  Memory Allocation in C Memory Allocation in C  Difference b\w static memory allocation.
Advertisements

C Characters & Strings Character Review Character Handling Library Initialization String Conversion Functions String Handling Library Standard Input/Output.
What is a pointer? First of all, it is a variable, just like other variables you studied So it has type, storage etc. Difference: it can only store the.
Current Assignments Homework 5 will be available tomorrow and is due on Sunday. Arrays and Pointers Project 2 due tonight by midnight. Exam 2 on Monday.
Pointers in C Rohit Khokher
Pointer applications. Arrays and pointers Name of an array is a pointer constant to the first element whose value cannot be changed Address and name refer.
Kernighan/Ritchie: Kelley/Pohl:
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:
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.
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.
C-strings Array with base type char One character per indexed variable
Introduction to C programming
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Tevfik Bultan Lecture 12: Pointers continued, C strings.
1 C - Memory Simple Types Arrays Pointers Pointer to Pointer Multi-dimensional Arrays Dynamic Memory Allocation.
Pointers and Arrays Beyond Chapter Pointers and Arrays What are the real differences? Pointer Holds the address of a variable Can be pointed.
Chapter 0.2 – Pointers and Memory. Type Specifiers  const  may be initialised but not used in any subsequent assignment  common and useful  volatile.
ECE 103 Engineering Programming Chapter 47 Dynamic Memory Alocation Herbert G. Mayer, PSU CS Status 6/4/2014 Initial content copied verbatim from ECE 103.
Dynamic memory allocation and Pointers Lecture 4.
Copyright 2005, The Ohio State University 1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation.
 2008 Pearson Education, Inc. All rights reserved Pointers and Pointer-Based Strings.
CPS4200 Unix Systems Programming Chapter 2. Programs, Processes and Threads A program is a prepared sequence of instructions to accomplish a defined task.
Computer Organization and Design Pointers, Arrays and Strings in C Montek Singh Sep 18, 2015 Lab 5 supplement.
Charles Clute Tom Most Michael Hein. Strings in C  There is no String... But there’s hope! Strings are character arrays char volume[6]; char volume[6]
Strings, Pointers and Tools
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 11: Pointers.
Arrays An array is a sequence of objects all of which have the same type. The objects are called the elements of the array and are numbered consecutively.
A FIRST BOOK OF C++ CHAPTER 7 ARRAYS. OBJECTIVES In this chapter, you will learn about: One-Dimensional Arrays Array Initialization Arrays as Arguments.
EC-111 Algorithms & Computing Lecture #10 Instructor: Jahan Zeb Department of Computer Engineering (DCE) College of E&ME NUST.
CS1010 Programming Methodology
Computer Organization and Design Pointers, Arrays and Strings in C
CSCI206 - Computer Organization & Programming
Strings CSCI 112: Programming in C.
Pointers & Arrays 1-d arrays & pointers 2-d arrays & pointers.
Fundamentals of Characters and Strings
ENEE150 Discussion 07 Section 0101 Adam Wang.
C Programming Tutorial – Part I
Programming Languages and Paradigms
CSE 303 Lecture 14 Strings in C
Programming Paradigms
Module 2 Arrays and strings – example programs.
CSCI206 - Computer Organization & Programming
Arrays in C.
Programming Languages and Paradigms
Lecture 6 C++ Programming
Clear1 and Clear2 clear1(int array[], int size) { int i; for (i = 0; i < size; i += 1) array[i] = 0; } clear2(int *array, int size) {
CS111 Computer Programming
Pointers Department of Computer Science-BGU יום רביעי 21 נובמבר 2018.
Pointers, Dynamic Data, and Reference Types
Pointers and Pointer-Based Strings
Week 9 – Lesson 1 Arrays – Character Strings
Dynamic Memory Allocation
Beginning C for Engineers
Dynamic Memory A whole heap of fun….
Pointers The C programming language gives us the ability to directly manipulate the contents of memory addresses via pointers. Unfortunately, this power.
C-strings In general, a string is a series of characters treated as a unit. Practically all string implementations treat a string as a variable-length.
CS111 Computer Programming
Arrays an array of 5 ints is filled with 3,2,4,1,7
String manipulation string.h library
Dynamic Memory A whole heap of fun….
Chapter 9: Pointers and String
C++ Programming Lecture 20 Strings
Strings #include <stdio.h>
Programming Languages and Paradigms
Characters and Strings Functions
EECE.2160 ECE Application Programming
Pointers, Dynamic Data, and Reference Types
Week 7 - Friday CS222.
SPL – PS2 C++ Memory Handling.
Chapter 16 Pointers and Arrays
Presentation transcript:

CSCI206 - Computer Organization & Programming C Arrays, String library, and Memory zyBook: 6.2, 6.9, 6.10, 6.12, 6.13

Partner Activity #include <stdio.h> char a[80]; int main(){ char b[80]; printf("a is at %p\n", &a[0]); printf("b is at %p\n", &b[0]); } This declares two 80 byte arrays of characters (strings). The output is: $ ./mem a is at 0x601060 b is at 0x7ffd5beafab0 Talk to your partner about what you think this might mean about how C variables are located in memory. format as a pointer (memory location) address of first character in array. Try out address.c

Memory Management Because C deals directly with memory, we have to understand the program’s view of memory To keep things organized, memory is split into (at least) 4 segments: Stack Heap Data Code

Memory Map Dynamic (runtime) allocation a is at 0x601080 b is at 0x7ffd23ea0ad0 Local (automatic) variables inside functions; activation records (recursion); unsafe to share between functions / modules Dynamic (runtime) allocation Dynamically allocated memory: malloc and free; safe to share between functions / modules Global variables Static (compile time) allocation Your program’s compiled machine code

Global data memory allocation #include <stdio.h> char a[80]; int main(){ //... } Data used multiple places (different functions) in your program. can be exported across modules (extern). Minimize use to keep your program clean.

Local memory allocation int main(){ char b[80]; //... } Data used within a single function. Unsafe to share with other functions! Use whenever possible to isolate variables to the function they belong.

Arrays dataType identifier[numElements]; Creates numElements of dataType sequentially in memory from some starting address. Array index starts at 0 (first element is [0]). e.g., char name[32]; name[0] = ‘A’;

sizeof sizeof(identifier) returns the total number of bytes in memory for identifier. e.g., char a; printf(“%d\n”, sizeof(a)); // prints 1 char *b; printf(“%d\n”, sizeof(b)); // prints 8 int nums[20]; printf(“%d\n”, sizeof(nums)); // prints 80 Try out sizeof.c

Array initialization int x[10]; // no intialization Warning, some of these are compiler specific and may behave differently on different compilers. Check the manual! Verify assumptions! int x[10]; // no intialization int x[10] = {};// no initialization int x[10] = {1,2,3,4,5,6,7,8,9,10}; int x[10] = {0}; // set first int to 0 int x[10] = {1}; // set first int to 1 Try out array-example.c

Alternate Initialization string.h has a useful function for initialization. void bzero(void *s, size_t n); n bytes starting from s set to zero void *memset(void *s, int c, size_t n); n bytes starting from s are set to the value c. memset(my_array, 42, sizeof(my_array)); // every byte in my_array set to 42

2d arrays As simple as adding an extra [x] in code float rain[5][12]; C stores arrays in row major order array[row][column] this means rows are stored together

float rain[5][12]; (logically) … rain[0][11] rain[1][0] rain[1][1] rain[1][2] rain[1][11] ... rain[4][0] rain[4][1] rain[4][2] rain[4][11] 5

float rain[5][12]; (logically) rain[1] is highlighted. … rain[0][11] rain[1][0] rain[1][1] rain[1][2] rain[1][11] ... rain[4][0] rain[4][1] rain[4][2] rain[4][11] 5

float rain[5][12]; (physically) N dimensional arrays are physically stored as a long 1 dimensional array in memory C translates your N-dimensional indexes to the correct offset from the beginning of the array (memory address) 5*12 rain[0][0] rain[0][1] rain[0][2] ... rain[0][11] rain[1][0] rain[1][1] rain[4][11]

Strings Don’t compare strings using == #include <string.h> char *str == char str[]; is *almost* the same thing… they can be used interchangeably. Strings char *str = “initial value”; char str[] = “initial value”; Don’t compare strings using == this will compare the address of the string. #include <string.h> strcmp - lexical order of strings, 0 if the same strcat - concatenate strings strstr - find a substring in a string strcpy - copy a string strtok - split a string using a delimiter

strtok example 1/2 #include <stdio.h> #include <string.h> int main() { char message[] = "Lorem ipsum dolor sit amet, consectetur adipiscing elit."; char* word; /* get the first word from the message, separated by * space character */ word = strtok(message, " "); printf("1st word: %s\n", word); 1st word: Lorem 1st call to strtok, pass the string (buffer) and delimiter. 1st matching token is returned (delimiters are removed).

char message[] = "Lorem ipsum dolor sit amet, consectetur adipiscing elit."; strtok example 2/2 /* get the second word from the message, NULL must be * used to get tokens from the previous string now */ word = strtok(NULL, " "); printf("2nd word: %s\n", word); /* the following loop gets the rest of the words until the * end of the message */ while ((word = strtok(NULL, " ")) != NULL) printf("Next: %s\n", word); } 2nd word: ipsum Next: dolor Next: sit Next: amet, Next: consectetur Next: adipiscing Next: elit. subsequent calls FOR THE SAME STRING, pass NULL as the string! The delimiter CAN change. YOU can only tokenize one string at a time! When there are no more tokens, strtok returns NULL Try out string.c

Strings - possible errors char *string; char *string = “initial value”; char string[100] = “initial value”; string = “new value”;

Strings - possible errors char *string; no memory is allocated. char *string = “initial value”; “initial value” is const, so as the variable string, can’t be changed. char string[100] = “initial value”; is 100 bytes enough? string = “new value”; don’t assign with strings (strncpy). until you understand pointers.