SBE201 Data Structures and Algorithms in C

Similar documents
ARRAYS(II Unit Part II)

Sir Syed University of Engineering and Technology. Computer Programming & Problem Solving ( CPPS ) Pointers. Chapter No 7

Parameter passing. Programming in C. Important. Parameter passing... C implements call-by-value parameter passing. UVic SEng 265

I2204 ImperativeProgramming Semester: 1 Academic Year: 2018/2019 Credits: 5 Dr Antoun Yaacoub

Gabriel Hugh Elkaim Spring CMPE 013/L: C Programming. CMPE 013/L: C Programming

Procedural Programming & Fundamentals of Programming

[0569] p 0318 garbage

Create a Program in C (Last Class)

Engineering program development 6. Edited by Péter Vass

C++ Arrays. Arrays: The Basics. Areas for Discussion. Arrays: The Basics Strings and Arrays of Characters Array Parameters

Intermediate Programming, Spring 2017*

Variation of Pointers

ECE 15B COMPUTER ORGANIZATION

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

type arrayname [ size type arrayname [ size ] = { item ,, item size size

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

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

Computers Programming Course 10. Iulian Năstac

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

EM108 Software Development for Engineers

Chapter IV Introduction to C for Java programmers

Week 8: Arrays and File I/O. BJ Furman 21OCT2009

Arrays and Pointers in C. Alan L. Cox

Pointers. Memory. void foo() { }//return

Pointers. 1 Background. 1.1 Variables and Memory. 1.2 Motivating Pointers Massachusetts Institute of Technology

Bil 104 Intiroduction To Scientific And Engineering Computing. Lecture 7

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

Output of sample program: Size of a short is 2 Size of a int is 4 Size of a double is 8

Pointers. Reference operator (&) ted = &andy;

today cs3157-fall2002-sklar-lect05 1

ONE DIMENSIONAL ARRAYS

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

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

by Pearson Education, Inc. All Rights Reserved.

Pointer Basics. Lecture 13 COP 3014 Spring March 28, 2018

Computer Programming Unit 3

FORM 1 (Please put your name and section number (001/10am or 002/2pm) on the scantron!!!!) CS 161 Exam II: True (A)/False(B) (2 pts each):

Memory, Arrays & Pointers

Pointers in C/C++ 1 Memory Addresses 2

Procedural programming with C

Reference operator (&)

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

A Fast Review of C Essentials Part I

CSE101-Lec#17. Arrays. (Arrays and Functions) Created By: Amanpreet Kaur & Sanjeev Kumar SME (CSE) LPU. LPU CSE101 C Programming

Homework #3 CS2255 Fall 2012

Arrays. An array is a collection of several elements of the same type. An array variable is declared as array name[size]

Computers Programming Course 11. Iulian Năstac

Tutorial 10 Pointers in C. Shuyue Hu

(13-2) Dynamic Data Structures I H&K Chapter 13. Instructor - Andrew S. O Fallon CptS 121 (November 17, 2017) Washington State University

Lectures 5-6: Introduction to C

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

CS107 Handout 08 Spring 2007 April 9, 2007 The Ins and Outs of C Arrays

Arithmetic Expressions in C

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

Pointers. 10/5/07 Pointers 1

QUIZ on Ch.8. What is kit?

Slide Set 2. for ENCM 335 in Fall Steve Norman, PhD, PEng

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

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

Comp 11 Lectures. Mike Shah. June 26, Tufts University. Mike Shah (Tufts University) Comp 11 Lectures June 26, / 57

Ricardo Rocha. Department of Computer Science Faculty of Sciences University of Porto

Write a C program using arrays and structure

C Programming Review CSC 4320/6320

Why Pointers. Pointers. Pointer Declaration. Two Pointer Operators. What Are Pointers? Memory address POINTERVariable Contents ...

Procedural Programming

Lectures 5-6: Introduction to C

Topics so far. Review. scanf/fscanf. How data is read 1/20/2011. All code handin sare at /afs/andrew/course/15/123/handin

by Pearson Education, Inc. All Rights Reserved.

Advanced Pointer Topics

Chapter 10. Arrays and Strings

Binary Representation. Decimal Representation. Hexadecimal Representation. Binary to Hexadecimal

Decimal Representation

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

Arrays. CS10001: Programming & Data Structures. Pallab Dasgupta Dept. of Computer Sc. & Engg., Indian Institute of Technology Kharagpur

Computers Programming Course 12. Iulian Năstac

KOM3191 Object Oriented Programming Dr Muharrem Mercimek ARRAYS ~ VECTORS. KOM3191 Object-Oriented Computer Programming

Lab 3. Pointers Programming Lab (Using C) XU Silei

Binghamton University. CS-211 Fall Pointers

Lecture 2: C Programm

CS 31: Intro to Systems Arrays, Structs, Strings, and Pointers. Kevin Webb Swarthmore College March 1, 2016

arrays and strings week 3 Ritsumeikan University College of Information Science and Engineering Ian Piumarta 1 / 22 imperative programming review

COMP26120: Pointers in C (2018/19) Lucas Cordeiro

Arrays and Pointers. CSC209: Software Tools and Systems Programming (Winter 2019) Furkan Alaca & Paul Vrbik. University of Toronto Mississauga

C Pointers. CS 2060 Week 6. Prof. Jonathan Ventura

Single Dimension Arrays

Outline. Computer programming. Debugging. What is it. Debugging. Hints. Debugging

Fundamentals of Programming & Procedural Programming

First of all, it is a variable, just like other variables you studied

EL2310 Scientific Programming

Chapter 2 (Dynamic variable (i.e. pointer), Static variable)

Data Types and Computer Storage Arrays and Pointers. K&R, chapter 5

C Program Development and Debugging under Unix SEEM 3460

Quiz 0 Review Session. October 13th, 2014

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!

Functions. Introduction :

Question 1. [15 marks]

Pointers. Pointer References

Pointers, Arrays, and Strings. CS449 Spring 2016

Fundamental of Programming (C)

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

Transcription:

SBE201 Data Structures and Algorithms in C Tutorial 3 Dina S. El-Kholy, Islam S. Badreldin Biomedical Engineering Department Faculty of Engineering Cairo University March 13, 2010

Copyright Copyright c 2010 Dina S. El-Kholy, Islam S. Badreldin. Some rights reserved. This work is licensed under a Creative Commons Attribution-Share Alike 3.0 License

Outline 1 Arrays Introduction Array Representation in Memory Reading and Writing 2 Strings Strings as Character Arrays The Null Termination Character String Manipulation 3 Pointers Introduction Pointer Dereferencing Pointers and Arrays Pointers and Strings Bad Pointers and the NULL Pointer

Arrays Outline 1 Arrays Introduction Array Representation in Memory Reading and Writing 2 Strings Strings as Character Arrays The Null Termination Character String Manipulation 3 Pointers Introduction Pointer Dereferencing Pointers and Arrays Pointers and Strings Bad Pointers and the NULL Pointer

Arrays Introduction Array Introduction Sometimes we want to be able to refer to a number of similar data elements collectively It will not be convenient to have a unique variable name for each element The Arrays are useful in such situations Arrays are collection of variables of a certain type that are placed contiguously in memory In order to define an array, like a variable, the compiler needs to know the data type of the elements contained in the array and the size of the array.

Arrays Introduction Array definition Example Let us define an array for the students marks, float marks[100]; The array definition involves the array elements data type (float), the array name (marks), and the array size enclosed in squared brackets (100)

Arrays Introduction Array initialization We can initialize the array as follows: int numbers[4]={1,2,3,4,5; Also we can omit the array size from the initialization, the compiler will simply count the number of elements you placed in the array and use it as the array size: int numbers[]={1,2,3,4,5;

Arrays Array Representation in Memory How does the array look like in the memory? Consider we declare an array s of type int and a size of 4 as follows Example int s[3]; Here is how the array will look like in the memory:

Arrays Array Representation in Memory Accessing array elements We can access individual array elements through indexing The first element index in C is zero, so to access element number zero of an array we use the statement: array_name[0] The last element index in C is size of array-1, so to access the last element of an array we use the statement: array_name[size of array-1]

Arrays Array Representation in Memory Array elements are contiguous in memory! Try out the following example. Note that the operator & gets the address of the variable in memory Example #include <stdio.h> int main(){ int s[4]; printf("%x\n",&s[0]); printf("%x\n",&s[1]); printf("%x\n",&s[2]); printf("%x\n",&s[3]); return 0; Examine the output: the addresses are consecutive and separated by 4 bytes since we declared an int array

Arrays Array Representation in Memory How does the compiler calculate the address of each element in the array? Examine the addresses obtained from the previous program Each element in the array has a distinct address but all are related! The first element of the array is given an address known as the base address Also, using the array name alone is equivalent to the address of the first element of the array To get the address of element i in the array we define the offset=i, then the address of element i is: Calculating the address base address + offset sizeof(array data type)

Arrays Array Representation in Memory Try this out! This example illustrates that the array name is equivalent to the address of the first array element! Example #include <stdio.h> int main(){ long int s[4]; printf("the array first element address \%x \n",&s[0]); printf("the value of the array name \%x \n",s); return 0;

Arrays Reading and Writing Reading and writing data to an array Try out this example, we will place values from 0 to 10 in the array and then print them out on the screen Example #include <stdio.h> int main(){ char arrays[11]; // size of the array=11 int i,j; for(i=0;i<11;i++) // loop stops at index size-1=11-1=10 { arrays[i]=i*i+5; for(j=0; j<=10;j++) // loop stops at index size-1=11-1=10 { printf("%d \n",arrays[j]);

Arrays Reading and Writing Out-of-bounds problem As a part of the array declaration, you are the one who decides the size of the array, that is the array size cannot be changed in runtime We emphasize that the array elements can be accessed through indexing the array from array[0] till array[size-1] What happens when you try to access an array location out of the size of the array?

Arrays Reading and Writing Try out this example Example #include <stdio.h> int main(){ int i,s[4],t[4],u=0; for(i=0; i<=4 ; i++)//note:we accesselement#5 of the array!! { s[i]=i; t[i]=i; printf("s:t \n"); for(i=0; i<=4;i++) { printf("%d:%d\n",s[i],t[i]); printf("%x %x", &s[0],&t[4]);

Arrays Reading and Writing Remarks In the previous example, We tried to access s[4] and t[4]. Both are not in the arrays bounds (size of the array=4) The C compiler did not complain but the content of s[0] is not right! Remember: you should always make sure you are not accessing an element outside of the array bounds, the compiler will not warn you and you will get wrong results, or the program may crash!

Strings Outline 1 Arrays Introduction Array Representation in Memory Reading and Writing 2 Strings Strings as Character Arrays The Null Termination Character String Manipulation 3 Pointers Introduction Pointer Dereferencing Pointers and Arrays Pointers and Strings Bad Pointers and the NULL Pointer

Strings Strings as Character Arrays Strings Strings are the form of data used in programming languages for storing and manipulating text such as words, names, and sentences In C, strings are represented by arrays of characters, meaning that is an array of type char So far, we only dealt with constant strings, like "Greetings!" in this example: Example printf("%s","greetings");

Strings Strings as Character Arrays Strings Now, how is the constant string Greetings represented in memory? this is how it looks like in the memory: What is the last character( 0 ) in the array? This is the null termination character

Strings The Null Termination Character The null termination character The null character stands for the character with numerical value zero Both the expressions char c= \0 and char c=0 are equivalent! They both place a numerical value of zero inside the variable c, which is called the null termination character Any string is automatically ended with this null character The null character is used to mark the ending of the string So, when you allocate a character array for your string, do not forget to count the null character!

Strings The Null Termination Character Declaring and initializing a string variable The are 2 possible ways to declare and initialize a string variable: char string[]={ c, a, t, \0 ; char string[]="cat"; The 2 ways are equivalent, in the second case the double quotes let the compiler know that this is a special char array which is a string and so the compiler will automatically terminate the string for you by the null terminator Also, no need to specify the array size for the compiler, the compiler will count the number of characters which is equal to 3 here and add the null character which makes the char array size equals 4

Strings String Manipulation String functions In order to work with strings, The C library contains a few basic string manipulation functions, these functions can be found in the <string.h> header file The function strlen is one famous function that returns the length of the string not including the null terminator C never lets you assign entire arrays, so the function strcpy(string2,string1) will let you copy string1 to string2, but make sure that string2 is allocated big enough to hold string1 Try to check strcat and strcmp as well!

Strings String Manipulation Strings example Example #include <stdio.h> #include <string.h> int main(){ char yourname[5]; strcpy(yourname,"name"); int i; int string_length; string_length=strlen(yourname); for(i=0;i<string_length+1;i++) { printf("%c:%i\n",yourname[i],yourname[i]);

Pointers Outline 1 Arrays Introduction Array Representation in Memory Reading and Writing 2 Strings Strings as Character Arrays The Null Termination Character String Manipulation 3 Pointers Introduction Pointer Dereferencing Pointers and Arrays Pointers and Strings Bad Pointers and the NULL Pointer

Pointers Introduction Pointers Up till now, we accessed variables in memory directly using the variable name Pointers provide a way of accessing a variable in an indirect way without referring to the variable itself but using the address of the variable in memory So, a pointer is a variable (location in memory) that holds an address of the location of some other variable The variable pointed to by the pointer can be of any data type

Pointers Introduction Pointer constant and pointer variable A pointer constant is an address while a pointer variable is a memory location that stores addresses The array name is a constant pointer (address) to the first element of an array. You can not modify its value since the linker decides where the array will go and it will stay there during the program execution C enables you to define pointer variables where you can store addresses and also modify these addresses

Pointers Introduction Defining Pointer variables The pointer variable definition looks like: <data type> * pointer variable name; The asterisk* sign tells the compiler that this variable will hold an address and not a value The data type tells the compiler that the address carried in this pointer variable is the address of a variable of this particular data type

Pointers Introduction What is the size of the pointer variable in memory? Example #include <stdio.h> int main(){ int *x; float *y; double *z; char *l; printf("the size of pointer to an int=%i\n",sizeof(x)); printf("the size of pointer to float=%i\n",sizeof(y)); printf("the size of pointer to double=%i\n",sizeof(z)); printf("the size of pointer to char=%i\n",sizeof(l)); return 0;

Pointers Introduction The & operator We said that pointer variables carry the address of some other variable, so to assign the an address of the variable to a pointer we use the & operator Example char a=17; char *b=&a; Here is how this may look like in the memory:

Pointers Pointer Dereferencing Pointer dereferencing We can access the variable pointed to by the pointer by using the * operator The *symbol has two uses, one is to tell the compiler that this variable is a pointer and the other is to access the variable pointed to by the pointer, the compiler can differentiate between them depending on the context of their appearance Example #include <stdio.h> int main(){ int x=5; int* p=&x; *p=(*p)*(2); printf("the value of x is %i",x);

Pointers Pointer Dereferencing Pointer and functions We saw before with function that we can only return one single value form the called function to the calling function, what if we want more that one variable to be modified by the called function? One solution is to use pointers as the function input arguments, here is an example:

Pointers Pointer Dereferencing Example #include <stdio.h> void rets2(int* px,int* py)//the function inputs are pointers {*px=3; /*derefrencing the pointer to access the variable x in main()*/ *py=5; int main() { int x=0; int y=0; rets2(&x,&y);//passing the addresses of x and y to the function printf("\nthe value of x is %i and y is %i \n",x,y);

Pointers Pointers and Arrays Pointers with arrays The following 2 examples serve the same purpose: Example #include <stdio.h> int main(){ int nums[]={92,81,70,69,58; int index; for (index=0;index<5;index++) { printf("\n%d",nums[index]);

Pointers Pointers and Arrays Example #include <stdio.h> int main(){ int nums[]={92,81,70,69,58; int index; for (index=0;index<5;index++) { printf("\n%d",*(nums+index));

Pointers Pointers and Arrays

Pointers Pointers and Arrays Arrays as constant pointers Example #include <stdio.h> int main (){ int numbers[]={10,20,30,40,50,-1; int index=0; while(*(numbers+index)>0) { printf("non-negative numbers are %i\n",*(numbers+index)); index++;

Pointers Pointers and Arrays Arrays as constant pointers The previous example had no problem, now try this: Example #include <stdio.h> int main (){ int numbers[]={10,20,30,40,50,-1; while(*(numbers++)>0) { printf("non-negative numbers are %i\n",*(numbers++));

Pointers Pointers and Arrays Try out this example Example #include <stdio.h> int main() { char *array="mona"; int i; for(i=0;i<=3;i++) {printf("%c \n",*(array++)); printf("%i \n",array); array--; printf("%c \n",*(array));

Pointers Pointers and Arrays Passing Arrays to functions This example illustrates how pointers can be used to let a function access and modify array elements: Example #include <stdio.h> #define SIZE 5 void addcon(int *ptr,int size,int con) {int k; for(k=0;k<size;k++) {*(ptr+k)=*(ptr+k)+con; int main () {int array[size]={3,5,7,9,11; int konst=10; int j; addcon(array,5,konst); for(j=0;j<size;j++){ printf("%d ",*(array+j));

Pointers Pointers and Strings Pointers and strings Example #include <stdio.h> int main(){ char *p="greetings"; printf("the whole string %s \n",p); printf("the first character of the string %c \n",*p); printf("the second character of the string is %c \n",*(p+1));

Pointers Bad Pointers and the NULL Pointer Bad pointers When a pointer is first allocated and not initialized, we call it a bad pointer Example We do not know where the bad pointer is pointing at Do not dereference a bad pointer. It may result in program crash! #include <stdio.h> int main(){ int* y; *y=*y+5; printf("%i",*y);

Pointers Bad Pointers and the NULL Pointer The NULL pointer The constant NULL is a special pointer value which encodes the idea of points to nothing The C language uses the NULL symbol for this purpose It is a runtime error to dereference a NULL pointer (Segmentation fault program crash) The NULL pointer is nothing more than assigning a decimal value of zero as the address inside the pointer variable

Appendix For Further Reading Further Reading Robert Lafore. C Programming Using Turbo C++. Wikibooks Contributors. C Programming. Wikibooks, Online: http://en.wikibooks.org/wiki/c Programming