Arrays, Strings, & Pointers

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

CMSC 313 COMPUTER ORGANIZATION & ASSEMBLY LANGUAGE PROGRAMMING LECTURE 11, FALL 2012

C mini reference. 5 Binary numbers 12

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

NEXT SET OF SLIDES FROM DENNIS FREY S FALL 2011 CMSC313.

8. Characters, Strings and Files

10/6/2015. C Input/Output. stdin, stdout, stderr. C Language II. CMSC 313 Sections 01, 02. C opens three input/output devices automatically:

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

C Programming. Unit 9. Manipulating Strings File Processing.

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

Chapter 8 C Characters and Strings

Chapter 8 - Characters and Strings

1 Pointer Concepts. 1.1 Pointer Examples

Programming in C. Pointers and Arrays

C PROGRAMMING. Characters and Strings File Processing Exercise

CSC 2400: Computer Systems. Arrays and Strings in C

Scientific Programming in C V. Strings

Contents. A Review of C language. Visual C Visual C++ 6.0

today cs3157-fall2002-sklar-lect05 1

CSC 2400: Computer Systems. Arrays and Strings in C

ONE DIMENSIONAL ARRAYS

ITC213: STRUCTURED PROGRAMMING. Bhaskar Shrestha National College of Computer Studies Tribhuvan University

COMP1917: 09 Arrays and Strings

Characters and Strings

C programming basics T3-1 -

Strings. Chuan-Ming Liu. Computer Science & Information Engineering National Taipei University of Technology Taiwan

211: Computer Architecture Summer 2016

C: How to Program. Week /May/28

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

3/22/2016. Pointer Basics. What is a pointer? C Language III. CMSC 313 Sections 01, 02. pointer = memory address + type

Strings. Steven R. Bagley

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

C: Arrays, and strings. Department of Computer Science College of Engineering Boise State University. September 11, /16

10/20/2015. Midterm Topic Review. Pointer Basics. C Language III. CMSC 313 Sections 01, 02. Adapted from Richard Chang, CMSC 313 Spring 2013

C Characters and Strings

CS 261 Fall Mike Lam, Professor. Structs and I/O

Why arrays? To group distinct variables of the same type under a single name.

AIR FORCE SCHOOL,BAMRAULI COMPUTER SCIENCE (083) CLASS XI Split up Syllabus (Session ) Contents

Copyright The McGraw-Hill Companies, Inc. Permission required for reproduction or display.

C Concepts - I/O. Lecture 19 COP 3014 Fall November 29, 2017

Fundamentals of Programming. Lecture 11: C Characters and Strings

Split up Syllabus (Session )

Array Initialization

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

Fundamentals of Programming

C Libraries. Bart Childs Complementary to the text(s)

CMSC 313 COMPUTER ORGANIZATION & ASSEMBLY LANGUAGE PROGRAMMING LECTURE 13, FALL 2012

Input / Output Functions

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

Fundamental of Programming (C)

Multiple Choice Questions ( 1 mark)

Model Viva Questions for Programming in C lab

SWEN-250 Personal SE. Introduction to C

C: Pointers, Arrays, and strings. Department of Computer Science College of Engineering Boise State University. August 25, /36

Arrays and Pointers (part 2) Be extra careful with pointers!

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

To declare an array in C, a programmer specifies the type of the elements and the number of elements required by an array as follows

Arrays and Pointers (part 2) Be extra careful with pointers!

Course organization. Course introduction ( Week 1)

Announcements. Strings and Pointers. Strings. Initializing Strings. Character I/O. Lab 4. Quiz. July 18, Special character arrays

gcc hello.c a.out Hello, world gcc -o hello hello.c hello Hello, world

POINTER AND ARRAY SUNU WIBIRAMA

Lecture 05 Pointers ctd..

CMSC 313 COMPUTER ORGANIZATION & ASSEMBLY LANGUAGE PROGRAMMING LECTURE 13, SPRING 2013

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

C Programming Language Review and Dissection III

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.

Characters in C consist of any printable or nonprintable character in the computer s character set including lowercase letters, uppercase letters,

mith College Computer Science CSC270 Spring 2016 Circuits and Systems Lecture Notes, Week 11 Dominique Thiébaut

Arrays and Pointers. CSE 2031 Fall November 11, 2013

B.V. Patel Institute of Business Management, Computer & Information Technology, Uka Tarsadia University

CSCI 6610: Intermediate Programming / C Chapter 12 Strings

CYSE 411/AIT681 Secure Software Engineering Topic #12. Secure Coding: Formatted Output

2/9/18. CYSE 411/AIT681 Secure Software Engineering. Readings. Secure Coding. This lecture: String management Pointer Subterfuge

Introduction to string

Approximately a Test II CPSC 206

CSC209H Lecture 4. Dan Zingaro. January 28, 2015

Standard C Library Functions

Arrays and Strings. Antonio Carzaniga. February 23, Faculty of Informatics Università della Svizzera italiana Antonio Carzaniga

ARRAYS(II Unit Part II)

Pointers and File Handling

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

The detail of sea.c [1] #include <stdio.h> The preprocessor inserts the header file stdio.h at the point.

Arrays and Pointers. Arrays. Arrays: Example. Arrays: Definition and Access. Arrays Stored in Memory. Initialization. EECS 2031 Fall 2014.

Computer Programming

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

A function is a named group of statements developed to solve a sub-problem and returns a value to other functions when it is called.

PRINCIPLES OF OPERATING SYSTEMS

Arrays and Pointers in C. Alan L. Cox

Muntaser Abulafi Yacoub Sabatin Omar Qaraeen. C Data Types

The Design of C: A Rational Reconstruction (cont.)

ch = argv[i][++j]; /* why does ++j but j++ does not? */

C Language Part 1 Digital Computer Concept and Practice Copyright 2012 by Jaejin Lee

Strings and Library Functions

PES INSTITUTE OF TECHNOLOGY (BSC) I MCA, First IA Test, November 2015 Programming Using C (13MCA11) Solution Set Faculty: Jeny Jijo

Reading Assignment. Strings. K.N. King Chapter 13. K.N. King Sections 23.4, Supplementary reading. Harbison & Steele Chapter 12, 13, 14

File IO and command line input CSE 2451

Variables and literals

C for C++ Programmers

Transcription:

Arrays, Strings, & Pointers Alexander Nelson August 31, 2018 University of Arkansas - Department of Computer Science and Computer Engineering

Arrays, Strings, & Pointers Arrays, Strings, & Pointers are all connected in C Pointer Variable storing a memory location Array Block of memory storing associated variables Array identifier is a pointer to location of first element String Array of character variables 1

Example #include <stdio.h> int main(){ char* mystring1 = "Hello!\n"; char mystring2[] = "Hello!\n"; printf("%s",mystring1); printf("%s",mystring2); return 0; } mystring1 and mystring2 are equivalent statements! 2

Pointers

Pointers Pointer Variable that points to a memory location Requires: Name Name of the pointer variable Type Type of the variable that is being addressed, with appended asterisk e.g. int* mypointer; Variable size in memory is not based on type, but on memory size Why? 3

Dereferencing Pointers Pointer stores memory location not value Dereferencing Obtaining value at a memory location Dereference Operators: Unary Operator (*) e.g. *myptr = 5; //Dereferences myptr and sets value to 5 Bracket offset e.g. myptr[0] = 5; //Dereferences to value at // myptr+offset*sizeof(objective type) 4

Address of Variable address accessed through ampersand (&) operator Literally the address of the variable Example: int val = 5; int* myptr = &val; //myptr now is equal to memory location of val 5

Pointer Example int val = 10; int* myptr = &val; //declare pointer to val *myptr = 5; //dereference pointer and set //that location = 5 printf("val =%d",val);//print val=(value of val) Output =? 6

Objective Type Objective Type type of variable pointed at e.g. int* p; //objective type = int int a[10]; //objective type = int int**p; //root objective type is int, objective type is int* Incrementing pointer variable increments by size of objective type e.g. Incrementing an int* increments value by sizeof(int) Incrementing an int** increments value by sizeof(int*) 7

Arrays

Arrays Array an ordered series or arrangement C Array Block of memory storing associated variables Accessed by same variable name Same data type 8

Declaration of Arrays Arrays must be declared before use Format: type variable name[length] type variable type of element to be stored variable name identifier of the array length number of elements to be stored Declaration and definition of array reserves a block of memory space according to type and length 9

Example Arrays double height[10]; type: double name: height length: 10 (memory size = 10 sizeof(double)) float width[30]; int c[9]; char name[20]; //string array 10

Array Implementation Array identifier stores address of first element Array identifier dereferenced by bracket operator obtains value 1st element stored at position 0, 2nd at 1, nth at (n-1)th element e.g. a[n] = (n+1)th element 11

Array Initialization Arrays should be initialized to some value Uninitialized arrays are able to be accessed, & contain garbage memory contents Examples: int a[] = {10,20,30,40}; int a[5] = {1,2,3}; If array size > num initialized, all others initialized to 0 int a[5] = {0}; Shorthand to initialize all to 0 12

Accessing Array Elements Accessed with a dereference operator and offset with [] operator Can be read & modified like a normal variable Valid Examples: c[0] = 3; c[3] += 5; y = c[x+1]; 13

Multidimensional Arrays Multidimensional arrays declared with each dimension e.g. int array[3][2]; Initialize each column through comma separated curly brace statements e.g. int array[3][2] = {{1,2},{3,4},{5,6}}; Memory-wise, the above is equivalent to: int array[6] = {1,2,3,4,5,6} 14

Shorthand multi-dimensional initialization Rules: Unspecified elements in given row initialized to 0 Unspecified rows initialized to 0 Examples: int array[3][2] = {{1},{3,4}} // == {1,0,3,4,0,0} int array[3][2] = {{0}} // == {0,0,0,0,0,0} 15

Passing Arrays to Functions Array identifier = pointer to first element Identifier (memory address) is passed by value = reference to array Array elements may be accessed by offset (known type) Length of array is not known! Use delimiter or pass length parameter(s) 16

Passing Array Elements Array elements are passed by value! Original memory location will not be modified Example: void myfunction(int a){ a = a+1; return a; } int main(){ int array[5] = {0}; myfunction(array[0]); printf("%d",array[0]); //Will print 0! } 17

Function with Const Array For arrays passed to functions with no intent to modify the array const keyword before array parameter e.g. int sum array(const int array[], int n); Compiler will throw error for any element modification operations 18

What is the difference? Identifier name points to first element Pointer points to any element Arithmetic operations on array name are disallowed 19

Example Difference int g, grades[ ] = {10, 20, 30, 40 }, mygrade = 100; int yourgrade = 85, *pgrades; /* grades can be (and usually is) used as array name */ for (g = 0; g < 4; g++) printf("%d\n",grades[g]); /* grades can be used as a pointer to its array if it doesn t change*/ for (g = 0; g < 4; g++) printf(%d\n", *(grades + g)); /* but grades can t point anywhere else */ grades = &mygrade; /* compiler error */ 20

Example Continued /* pgrades can be an alias for grades and used like an array name */ pgrades = grades; /* or pgrades = &(grades[0]); */ for( g = 0; g < 4; g++) printf( "%d\n", pgrades[g]); /* pgrades can be an alias for grades and be used like a pointer that ch for (g = 0; g < 4; g++) printf("%d\n",*(pgrades++)); /* BUT, pgrades can point to something else other than the grades array pgrades = &mygrade; printf( "%d\n", &pgrades); pgrades = &yourgrade; printf( "%d\n", &pgrades); 21

Array of Pointers Pointers are a data type & can be placed in an array e.g. ArrayList Especially useful for array of variable string sizes to reduce wasted bytes e.g. char* mystringarray[] or char** mystringarray 22

Strings

Strings/Char Arrays C doesn t have a string type Implemented using char arrays & string literals To be a string, a char array must be null terminated Example: char string1[] = hello world! ; char string2[] = { h, e, l, l, o,, w, o, r, l, d,!, \0 }; char string3[5] = hello ; //Error: 6 characters in string literal char string4[10] = hello ; // hello\0\0\0\0\0 23

ASCII American Standard Code for Information Interchange (ASCII) Encodes the Roman alphabet used in English/West European languages Has 128 characters Encoded as leading 0 and 7 bit value Chars 0-31 represent control characters (e.g. \n ) C was designed to work with ASCII The char data type is used to store ASCII characters in C 24

ASCII Table Decimal Hex Char Decimal Hex Char Decimal Hex Char Decimal Hex Char 25

Special Characters Backslash character ( \ ) used to indicate special character e.g. \n newline \t tab \ double quote \ single quote \\ backslash (since backslash has special meaning) \a beep (unprintable) 26

Character Library ctype.h C library of char functions Examples: int isdigit (int c) Is c a decimal digit ( 0-9 )? int isdigit(int c) Is c a hexadecimal digit ( 0-9, a - f, or A - F )? int isalpha (int c) Is c an alphabetic character ( a - z or A- Z )? int isspace (int c) Is c a whitespace character (space, tab, etc)? int isprint (int c) Is c a printable character? int tolower (int c) Change c to lower case if alpha int toupper (int c) Change c to upper case if alpha 27

String Output Use %s in printf() or fprintf() to print string Will print until NULL is seen Can provide field width and justification e.g. char book1[] = Dune ; char book2[] = Brave New World ; printf( Favorite Book: %12s, book1); printf( Other Book: %12s,book2); What will the above print? 28

scanf() scanf() stdio function for taking input from stdin Format: scanf( %s,string1); Reads characters from stdin until whitespace encountered Can write beyond end of array! Best case stack smashing detected Worst case Overwrites other memory 29

Example Program #include <stdio.h> int main(){ char string1[20], string2[]="string"; int i; printf("enter a string: "); scanf("%s", string1); printf("string1: %s\nstring2: %s\n",string1,string2); for(i=0;string1[i]!= \0 ;i++) printf("%c",string1[i]); // Print by iteration printf("\n"); return 0; } 30

scanf( %#s ) To avoid overflow, specify the number of characters! char buffer[100] = ; scanf( %99s,buffer); Why 99? 31

gets()/fgets() gets(char* buffer) read a line of input until \n Newline then replaced with null character Can overflow buffer! fgets(char* buffer, int len, FILE *stream) read a line of input from file until n-1 characters or \n Newline then replaced with null character Safer, as max length can be specified! File can be STDIN Returns NULL when EOF detected! 32

fgets() Example FILE *infile; infile = fopen( "myfile", "r" ); /* check that the file was opened */ char buffer[120]; while ( fgets(buffer, 120, infile )!= NULL ) printf( "%s\n", string ); fclose( infile ); Will read line-by-line up to 120 characters until EOF detected 33

sprintf() Format a string in an array of characters Akin to tostring() in Java sprintf() works like printf() but output goes to character array e.g. char buffer[100] = 0; int numstudents = 33; sprintf(buffer, There are %d students\n,numstudents); 34

C String Library string.h C String library Common string manipulation functions e.g. strlen( const char string[ ] ) Number of characters in string (not including null ) strcpy( char s1[ ], const char s2[ ] ) Copies s2 on top of s1 strcmp ( const char s1[ ], const char s2[ ] ) Returns < 0, 0, > 0 if s1 < s2, s1 == s2 or s1 > s2 lexigraphically strcat( char s1[ ], const char s2[ ]) Appends (concatenates) s2 to s1 35

C String Library Some functions have size parameter e.g. strncpy( char s1[ ], const char s2[ ], int n ) Copies at most n characters of s2 on top of s1 strncmp ( const char s1[ ], const char s2[ ], int n ) Compares up to n characters of s1 with s2 Returns < 0, 0, > 0 if s1 < s2, s1 == s2 or s1 > s2 lexigraphically strncat( char s1[ ], const char s2[ ], int n) Appends at most n characters of s2 to s1 36

Array of Strings Strings are arrays Array of Strings == Multi-dimensional array e.g. char months[10][] = { January, February, March, April, May, June, July, August, September, October, November, December }; //120 byte array w/ 2 indices 37

Command Line Arguments Command line arguments are passed to main as an array of strings int main(int argc, char* argv[]) argc number of arguments argv array of strings argv[0] always the name of the executable 38

Pointer Arithmetic

Pointer Arithmetic Incrementing a pointer increments by sizeof(objectivetype) e.g. char c, *cptr = &c; int i, *iptr = &i; float f, *fptr = &f; printf( %p,%p%p,cptr++,iptr++,fptr++); printf( %p,%p%p,cptr++,iptr++,fptr++); Outputs: 0x00, 0x10, 0x20 0x01, 0x14, 0x24 39

void Pointers Void pointers are special case C Standard does not allow arithmetic or dereferencing of void pointers However: GCC has an extension that allows arithmetic To dereference a void pointer, first cast to typed pointer, then dereference e.g. *(int *)myvoidpointer; (int)*myvoidpointer does not work! 40

Function Pointers Function identifiers are a pointer to instruction memory Can create a pointer to the instruction Type == Return type of function Also declared with parameters of function e.g. int myfunction(int param1); int (*myfunctionptr)(int) = &myfunction; int ret = (*myfunctionpointer)(10); 41