Pointers, Arrays, and Strings. CS449 Spring 2016

Similar documents
Arrays and Strings. CS449 Fall 2017

CSC209H Lecture 4. Dan Zingaro. January 28, 2015

CSCE150A. Introduction. Basics. String Library. Substrings. Line Scanning. Sorting. Command Line Arguments. Misc CSCE150A. Introduction.

Computer Science & Engineering 150A Problem Solving Using Computers. Chapter 9. Strings. Notes. Notes. Notes. Lecture 07 - Strings

Computer Science & Engineering 150A Problem Solving Using Computers

Create a Program in C (Last Class)

Dynamic Memory. Dynamic Memory Allocation Strings. September 18, 2017 Hassan Khosravi / Geoffrey Tien 1

Characters, Character Strings, and string-manipulation functions in C

Lecture07: Strings, Variable Scope, Memory Model 4/8/2013

8. Characters, Strings and Files

Programming in C. Session 7. Seema Sirpal Delhi University Computer Centre

Jagannath Institute of Management Sciences Lajpat Nagar. BCA II Sem. C Programming

Lecture 05 Pointers ctd..

COMP 2355 Introduction to Systems Programming

C Characters and Strings

Principles of C and Memory Management

Student Number: Instructor: Reid Section: L5101 (6:10-7:00pm)

Chapter 8: Character & String. In this chapter, you ll learn about;

upper and lower case English letters: A-Z and a-z digits: 0-9 common punctuation symbols special non-printing characters: e.g newline and space.

Memory, Arrays & Pointers

Characters and Strings

Character Array. C Programming. String. A sequence of characters The last character should be \0 that indicates the end of string 5 \0

Computer Programming: Skills & Concepts (CP) Strings

SYSTEM AND LIBRARY CALLS. UNIX Programming 2015 Fall by Euiseong Seo

Strings(2) CS 201 String. String Constants. Characters. Strings(1) Initializing and Declaring String. Debzani Deb

SYSC 2006 C Winter String Processing in C. D.L. Bailey, Systems and Computer Engineering, Carleton University

ECE551 Midterm Version 1

CS 33. Introduction to C. Part 5. CS33 Intro to Computer Systems V 1 Copyright 2017 Thomas W. Doeppner. All rights reserved.

Student Number: Instructor: Reid Section: L0101 (10:10-11:00am)

This code has a bug that allows a hacker to take control of its execution and run evilfunc().

Getting Started. Project 1

Student Number: Instructor: Reid Section: L0201 (12:10-1:00pm)

Procedural Programming

CS 0449 Sample Midterm

Procedural Programming & Fundamentals of Programming

Library Functions. General Questions

Computer Programming Unit 3

CSC209H1S Day Midterm Solutions Winter 2010

CS201 Lecture 2 GDB, The C Library

ECE 264 Exam 2. 6:30-7:30PM, March 9, You must sign here. Otherwise you will receive a 1-point penalty.

Agenda. Peer Instruction Question 1. Peer Instruction Answer 1. Peer Instruction Question 2 6/22/2011

C Pointers. Abdelghani Bellaachia, CSCI 1121 Page: 1

Bil 104 Intiroduction To Scientific And Engineering Computing. Lecture 7

C Programming Language Review and Dissection III

ECE551 Midterm Version 1

C strings. (Reek, Ch. 9) 1 CS 3090: Safety Critical Programming in C

Strings. Arrays of characters. Pallab Dasgupta Professor, Dept. of Computer Sc & Engg INDIAN INSTITUTE OF TECHNOLOGY

Pointer Arithmetic and Lexical Scoping. CS449 Spring 2016

Jacobs University Bremen February 7 th, 2017 Dr. Kinga Lipskoch. Practice Sheet. First Name:... Last Name:... Matriculation Number:...

CSCI 6610: Intermediate Programming / C Chapter 12 Strings

C BOOTCAMP DAY 2. CS3600, Northeastern University. Alan Mislove. Slides adapted from Anandha Gopalan s CS132 course at Univ.

Array Initialization

CSC 209H1 S 2012 Midterm Test Duration 50 minutes Aids allowed: none. Student Number: # 1: / 6

CS 137 Part 6. ASCII, Characters, Strings and Unicode. November 3rd, 2017

[6 marks] All parts of this question assume the following C statement. Parts (b) through (e) assume a variable called ptrs.

CS 61c: Great Ideas in Computer Architecture

ARRAYS(II Unit Part II)

CS 61C: Great Ideas in Computer Architecture. C Arrays, Strings, More Pointers

CS1100 Introduction to Programming

C introduction: part 1

Lecture 4: Outline. Arrays. I. Pointers II. III. Pointer arithmetic IV. Strings

CSC 209H1 S 2012 Midterm Test Duration 50 minutes Aids allowed: none. Student Number: # 1: / 7

CS201- Introduction to Programming Latest Solved Mcqs from Midterm Papers May 07,2011. MIDTERM EXAMINATION Spring 2010

Procedural programming with C

ECE551 Midterm Version 2

Intermediate Programming, Spring 2017*

Chapter 5. Section 5.1 Introduction to Strings. CS 50 Hathairat Rattanasook

Computers Programming Course 12. Iulian Năstac

Grade Distribution. Exam 1 Exam 2. Exams 1 & 2. # of Students. Total: 17. Total: 17. Total: 17

Programming. Pointers, Multi-dimensional Arrays and Memory Management

Pointers. Part VI. 1) Introduction. 2) Declaring Pointer Variables. 3) Using Pointers. 4) Pointer Arithmetic. 5) Pointers and Arrays

Computers Programming Course 11. Iulian Năstac

EM108 Software Development for Engineers

Chapter 16. Pointers and Arrays. Address vs. Value. Another Need for Addresses

DAY 3. CS3600, Northeastern University. Alan Mislove

Arrays. Example: Run the below program, it will crash in Windows (TurboC Compiler)

Princeton University Computer Science 217: Introduction to Programming Systems. Modules and Interfaces

Computer Programming. C Array is a collection of data belongings to the same data type. data_type array_name[array_size];

Arrays and Strings (2H) Young Won Lim 3/7/18

Arrays Arrays and pointers Loops and performance Array comparison Strings. John Edgar 2

Computer Security. Robust and secure programming in C. Marius Minea. 12 October 2017

Introduction to Programming Block Tutorial C/C++

Lecture 10 Arrays (2) and Strings. UniMAP SEM II - 11/12 DKT121 1

A. Year / Module Semester Subject Topic 2016 / V 2 PCD Pointers, Preprocessors, DS

Fundamental of Programming (C)

ECE551 Midterm. There are 7 questions, with the point values as shown below. You have 75 minutes with a total of 75 points. Pace yourself accordingly.

Tutorial 10 Pointers in C. Shuyue Hu

String constants. /* Demo: string constant */ #include <stdio.h> int main() {

Today s lecture. Continue exploring C-strings. Pointer mechanics. C arrays. Under the hood: sequence of chars w/ terminating null

int Return the number of characters in string s.

CS 449 Lecture 3. Variables in memory. Dr. Jack Lange. int x = 4;

For example, let s say we define an array of char of size six:

Princeton University Computer Science 217: Introduction to Programming Systems. Modularity design principles

ECE 15B COMPUTER ORGANIZATION

Hacking in C. Pointers. Radboud University, Nijmegen, The Netherlands. Spring 2019

Chapter 8 - Characters and Strings

BİL200 TUTORIAL-EXERCISES Objective:

Iosif Ignat, Marius Joldoș Laboratory Guide 9. Character strings CHARACTER STRINGS

Arrays and Pointers. CSE 2031 Fall November 11, 2013

Memory Allocation. General Questions

Transcription:

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. #include <stdio.h> int main () { int var1; printf("address of var1 variable: %x\n", &var1 ); } return 0; >>./a.out Address of var1 variable: ffbff854

Pointers A pointer is a variable whose value is the address of another variable. Pointer declaration: type *var-name;

Pointers Pointer declaration: type *var-name; Declaration examples: int *count; double *ratio; char *symbol;

Pointer Usage #include <stdio.h> int main () { int var = 20; /* actual variable declaration */ int *p; /* pointer variable declaration */ p = &var; /* store address of var in pointer variable*/ } printf("address of var variable: %x\n", &var ); printf("address stored in p variable: %x\n", p ); printf("value of *p variable: %d\n", *p ); return 0; >>./a.out Address of var variable: bffd8b3c Address stored in p variable: bffd8b3c Value of *p variable: 20

NULL Pointers Good practice! int *ptr = NULL; printf("the value of ptr is : %x\n", ptr ); >>./a.out The value of ptr is 0 To Test: if(ptr) /* succeeds if p is not null */ if(!ptr) /* succeeds if p is null */

Arrays Data type for a sequence of variables of a given type in consecutive memory Just as for pointers, there are array types for each primitive data type (e.g. char, int, float)

Running Example #include <stdio.h> int main() { >>./a.out Enter nums: 10 20 30 40 50 Your nums: 10 20 30 40 50 int nums[5], i; /* declarations */ printf("enter nums: "); for(i=0; i<5; ++i) { scanf("%d", &nums[i]); /* write to array */ } printf("your nums: "); for(i=0; i<5; ++i) { printf("%d ", nums[i]); /* read from array */ } return 0; }

Declaring Arrays #include <stdio.h> int main() { int nums[5], i; /* declarations */ printf("enter nums: "); for(i=0; i<5; ++i) { scanf("%d", &nums[i]); /* write to array */ } printf("your nums: "); for(i=0; i<5; ++i) { printf("%d ", nums[i]); /* read from array */ } return 0; } Syntax: <type> <name> [ <length> ] E.g. int num[5];, char c[10]; Combination of type and length tells the compiler amount of memory to reserve (sizeof(type) * length) Length must always be declared (explicitly or implicitly) Array initializers Handy way to initialize elements of array E.g. int num[3] = {1, 2, 3}; If initializer shorter than length, rest initialized to 0 (e.g. int num[3] = {1};, int num[3] = {}; ) Initializers implicitly gives size of array (e.g. int num[] = {1, 2, 3}; Initialized arrays can still be modified

Accessing Arrays #include <stdio.h> int main() { int nums[5], i; /* declarations */ printf("enter nums: "); for(i=0; i<5; ++i) { scanf("%d", &nums[i]); /* write to array */ } printf("your nums: "); for(i=0; i<5; ++i) { printf("%d ", nums[i]); /* read from array */ } return 0; } Syntax: <name> [ <index> ] E.g. nums[5], c[10] Index starts with 0 nums[i] accesses the i+1 th element Value of array name with no index (e.g. nums ) is the address of first element of array (equivalent to &nums[0] ) Is interchangeable with pointer int *p = nums; is perfectly valid *p == nums[0] Difference between array and pointer Array has allocated memory statically bound to the name at compile time nums cannot point to new address (e.g. nums = p results in compile error)

Declaring Multidimensional Arrays Syntax: <type> <name> [ <length1> ] [ <length2> ]... [ <lengthn> ] E.g. int nums[2][3]; Array initializers E.g. int nums[2][3] = { {0, 1, 2}, {3, 4, 5} }; Conceptual layout Physical layout in linear memory Column 0 Column 1 Column 2 Row 0 0 1 2 Row 1 3 4 5 0 1 2 3 4 5 [0][0] [0][1] [0][2] [1][0] [1][1] [1][2]

Accessing Multidimensional Arrays Syntax: <type> <name> [ <index1> ] [ <index2> ]... [ <indexn> ] E.g. to access nums[1][2]; we offset (1 * 3 + 2) = 5 in linear memory If we do: int (*p)[3] = nums; then p[1][2] == nums[1][2] == 5 If we do: int *p = nums[1]; then p[2] == 5 nums cannot be target of assignment int (*p)[3] int *p[3] Be careful: is a pointer to a 3 column array is an array of 3 pointers!!!

Strings There is no string data type in C Sequence of characters in consecutive memory ending with a null character ( \0 ); Null character: character constant with ASCII value 0 In short, a string is a null-terminated character array String variables are declared as character arrays e.g. char s[10]; can hold a string 9 characters long (excluding the null character) Character pointers ( char * ) can point to strings const char* points to an immutable string

String Functions Defined in C standard library, declared in <string.h> Prototype Description size_t strlen(const char *s); Calculates the length of the string s, not including the terminating '\0' character. int strcmp(const char *s1, const char *s2); int strncmp(const char *s1, const char *s2, size_t n); Compares the string pointed to by str1 to the string pointed to by str2. If return value < 0 then str1 is less than str2, if it is > 0 then str2 is less than str1, and if it is = 0 then str1 is equal to str2. Same as above, except only compares the first (at most) n characters of s1 and s2

String Functions Prototype char *strcpy(char *dest, const char *src); char *strncpy(char *dest, const char *src, size_t n); char *strcat(char *dest, const char *src); Description Copies the string pointed to by src (including the terminating '\0' character) to the array pointed to by dest. Same as above, except that not more than n bytes of src are copied. Appends the src string to the dest string overwriting the '\0' character at the end of dest, and then adds a terminating '\0' character. char *strncat(char *dest, const char *src, size_t n); Same as above, except that it will use at most n characters from src. Always try to use the n version to prevent buffer overruns

String Functions Prototype char *strchr(const char *s, int c); char *strstr(const char *haystack, const char *needle); Description Returns a pointer to the first occurrence of the character c in the string s. Finds the first occurrence of the substring needle in the string haystack.

String Conversion Functions String to number conversion functions declared in <stdlib.h> Prototype int atoi(const char *nptr); Description Converts string pointed to by nptr to int. double atof(const char *nptr); Converts string pointed to by nptr to double. String formatting functions declared in <stdio.h> Prototype int sprintf(char *str, const char *format,...); int snprintf(char *str, size_t size, const char *format,...); Description Same as printf except instead of writing to stdout formatted string is written to str Same as above, except no more than size bytes are written to str Not an exhaustive list. Use your manpages. (e.g. man string, man stdio )

Pitfall 1: Arrays What s wrong with the following code? int a[5]; a[5] = 0; a[5] is attempting to get a value from unallocated memory so result is undefined Remember index always starts with 0

Pitfall 2: String buffer allocation What s wrong with the following code? char *s1; char *s2 = Some long string of characters ; strcpy(s1, s2); s1 points to random unallocated memory Change pointer to array: char s1[100]; Additionally, change strcpy to strncpy: char s1[100]; strncpy(s1, s2, 100); // to prevent buffer overflow s1[99] = \0 ; // in case s2 is longer than 100 chars

Pitfall 3: String comparison What s wrong with the following code? char s[100]; strcpy(s, Hello ); if(s == Hello ) printf( Hello\n ); The value of s is just the address &s[0] Should do instead: if(strcmp(s, Hello ) == 0) printf( Hello\n );

Pitfall 2: String buffer allocation What s wrong with the following code? char *s1; char *s2 = Some long string of characters ; strcpy(s1, s2); s1 points to random unallocated memory Change pointer to array: char s1[100]; Additionally, change strcpy to strncpy: char s1[100]; strncpy(s1, s2, 100); // to prevent buffer overflow s1[99] = \0 ; // in case s2 is longer than 100 chars

Review of Data Types Primitive data types integers: char, short, int, long, long (signed and unsigned) reals: float, double, long double Pointers (derived type that points to another type) char *p, int *p, int (*p)[3], int (*p)[2][3], int **p Arrays (derived type that is a sequence of a given type) char a[3], int a[3], int a[2][3], int *a[3] (same as int *(a[3])) Given array int a[2][3][4], the following are valid int (*p)[3][4] = a; (same as int (*p)[3][4] = &[a];) int (*p)[4] = a[1]; (same as int (*p)[4] = &a[1][0];) int *p = a[1][0]; (same as int *p = &a[1][0][0]) int p = a[1][0][2];

Pitfall 4: No L-Value What s wrong with the following code? int n; int **p = &(&n); &n has no storage location (a.k.a. l-value) The following code is valid: int n; int *p = &n; int **p2 = &(p); By the same token, the following is invalid int a[3], b[3]; a = b; // a is not an l-value