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