Computer Programming: 8th Week Pointers Hazırlayan Asst. Prof. Dr. Tansu Filik
Computer Programming Previously on Bil-200 Recursive functions, two way communications with functions (reference)
Meanings of * Multiplication: Between two numbers, it is the multiplication operator. a * b Pointer: Corresponds to the pointer type variable. char *p; Pointer: Corresponds to the value of the variable pointed to by the pointer. *p = 5;
Computer Programming Pointers int *p1 /*Pointer to an integer variable*/ double *p2 /*Pointer to a variable of data type double*/ char *p3 /*Pointer to a character variable*/ float *p4 /*pointer to a float variable*/ Example-1 int main() { /*Pointer of integer type*/ int *p; int var = 10; /*Assigning the variable address to pointer*/ p= &var; printf("value of var is: %d", var); printf("address of var is: %d", p); return 0; Declerations #include <stdio.h> int main() { int var =10; int *p; p= &var; printf ( "\n Address of var is: %d", &var); printf ( "\n Address of var is: %d", p); printf ( "\n Address of pointer p is: %d", &p); printf( "\n Value of pointer p is: %d", p); printf ( "\n Value of var is: %d", var); printf ( "\n Value of var is: %d", *p); printf ( "\n Value of var is: %d", *( &var)); return 0; Address of var is: 00XBBA77 Address of var is: 00XBBA77 Address of pointer p is: 77221111 Value of pointer p is: 00XBBA77 Value of var is: 10 Value of var is: 10 Value of var is: 10
Example: Date Write a function to enter a date in the "dd/mm/yyyy" form. If the entered date s invalid, the function must warn by writing invalid and requesting a proper date. void input_date(int *gun, int *ay, int *yil);
Example: Date void input_dat(int *gun, int *ay, int *yil) { int gecerli; char ayrac1, ayrac2; do { gecerli = 1; printf("tarih girin(gg aa yyyy): "); scanf("%d %d %d", gun, ay, yil); if ( *gun < 0 *gun > 31 *ay< 1 *ay > 12 *yil < 0 *yil > 9999) { gecerli = 0; printf("tarih yanlis\n"); while (!gecerli);
Example: Date void input_date(int *gun, int *ay, int *yil) { gun is a pointer variable. It contains the the address of the variable.... scanf("%d %d %d", gun, ay, yil);... Why didn t we use &? The & sign is used for accessing the address of the variable. The gun variable is already an address.
Example: Polynomial roots Write a function which takes three float type variables a, b, c from the main program, and returns the real roots of the second order polynomail identified by these coefficients. The function will have three input and two output parameters. input parameters void kok_bul(float a, float b, float c, float &x1, float &x2); output parameters
Example: Polynomial roots #include <stdio.h> void kok_bul(float a,float b,float c, float *x1, float *x2); void main() { float x, y, z, k1, k2; printf("a b c girin: "); scanf("%f %f %f", &x, &y, &z); kok_bul(x, y, z, &k1, &k2); prototype values addresses printf("kokler: %f %f\n", k1, k2);
Example: Polynomial roots void kok_bul(float a, float b, float c, float *x1, float *x2) { float delta; delta = b * b 4 * a * c; if(delta < 0) { *x1 = 0; *x2 = 0; return; *x1 = (-b + sqrt(delta)) / ( 2 * a ); *x2 = (-b - sqrt(delta)) / ( 2 * a );
Introduction to Programming Languages #include <stdio.h> #include <math.h> void kok_bul(double a, double b, double c, double *x1, double *x2); void main(void) { double x, y, z, k1, k2; printf("a - b - c girin: "); scanf_s("%lf %lf %lf", &x, &y, &z); kok_bul(x, y, z, &k1, &k2); printf("kokler: %f %f\n", k1, k2); system("pause"); void kok_bul(double a, double b, double c, double *x1, double *x2) { double delta; delta = b * b - 4 * a * c; if (delta < 0) { *x1 = 0; *x2 = 0; return; *x1 = (-b + sqrt(delta)) / (2 * a); *x2 = (-b - sqrt(delta)) / (2 * a);
Class exercise: division Write a function bolum()with the following parameter list of integers: sayi: to be divided bolen: number to divide with sonuc: division result kalan: remainder The function must implement the integer division. It should divide sayi to bolen, and return the division in sonuc, remainder in kalan.
Character arrays We have been using them for a long time, but...
Character arrays character array printf("sayi=%d!\n", i, j); We have not seen character array type (string) variables yet, but we have been using them for some time. They are defined like: char isim[100];
Strings Like other arrays, initial assignments can be made: char isim[20] = mehmet"; In memory null character (terminates array) isim m e h m e t \0????????????? 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 space allocated for the array
Strings In the declaration and initial assignment line, the compiler terminates the string with the null character. There is a standard string library in C. The defined functions work with the fact that end of string is a null character. The characters to its right are ignored. Since a null character is necessary to terminate a string, you must allocate a space at least 1 more than the maximum number of letters. For example, by saying "char isim[20];" we can hold names of length up to 19 (+ null character).
String declarations String can be initialized in several ways. char renk[ ] = "kırmızı" ; OR char *renk = "kırmızı" ; OR char renk[8] = {'k','ı','r','m','ı','z','ı','\0' ; In the first two methods, the necessary memory space is calculated according to the initial constant string (+1) In the third declaration, we must allocate sufficient space carefully.
void getstring(char *str, int max_len) { int i=0; do { str[i]=getche(); /* conio.h */ i++; while((str[i-1]!= \n )&&(i<max_len-1)); str[i-1]= \0 ; void main(void) { char my_string[100]; getstring( &( my_string [0]),100); printf( %s\n,my_string);
Exercise Write a function which converts an entered string into an integer assuming the entered string is proper. a float, assuming the entered string is proper. Write the two functions in such a way that they ignore improper entries. As examples, the strings at the left would be recognized as numbers at the right: 123se24 => 12324, 12.143ser.43 => 12.14343 Note: Functions such as i=atoi(str), or x=atof(str) can normally do this, but they are not allowed. They do not tolerate improper entries. Note: sscanf(str, %d,&i) or sscanf(str, %f,&x) are not allowed, either.
Note: sscanf and sprintf are two very powerful functions used for extracting variables from a string or to form a string with many variables. : i=10; j=20; x=3.14; char *str2= 101,32 21.13 olabilir ; sprintf(str, Degisken i=%d, j=%d, x=%f,i,j,x); printf( %s\n,str); sscanf(str2, %d,%d %f,&i,&j,%x);
String manipulation functions string.h must be included as a header. String copy: Used for copying contents of the second string str2 into the first string str1: char *strcpy(char *str1,const char *str2); String concatenation: str2 is appended to the last part of str1 char *strcat(char *str1,const char *str2);
String functions Length of a string str (except the null character) is evaluated. int strlen(const char *str1); To lexicographically compare to strings, use strcmp(). If str1 and str2 have the same content, strcmp() returns 0. strcmp(const char *str1,const char *str2);
#include <stdio.h> #include <string.h> void main() { char ad[100]; Example strcmp() printf("adınızı Yazınız: "); gets(ad); /* read one line */ if(strcmp(ad, Mehmet") == 0) { printf( Selam Mehmet");
Example: strlen #include <stdio.h> #include <string.h> void main() { char ad[100]; printf("adinizi Yazınız: "); gets(ad); /* read one line */ printf("ad Uzunluğu = %d\n",strlen(ad));
Exercise (difficult) Open a text file. Ask the user to enter two strings. Replace all first strings with the second string inside the file (find / replace) Note: Assuming the file is small, you can read the whole text file into a single string. But, you do not have to do that. The usage is like: Ali topu at, koş Ali koş. Ali -> Veli Veli topu at, koş Veli koş. (or) Ali -> O O topu at, koş O koş.
Midterm Exam-2 Questions (2013-2014)
Midterm Exam-2 Questions (2013-2014)
Midterm Exam-2 Questions (2013-2014)
static and automatic variables, and scope
Rem: Static variables We have seen that local variables are lost when exitting a function. Static variables are re-formed every time when entering the same function. They are different from automatic variables. These variables are formed at the beginning of the program, and their values are set. Obviously, they are valid only inside its declared function.
void fonk_yaz(void) { int a = 0; printf("deger = %d\n", a); a++; void main() { int i; for( i = 0 ; i < 3 ; i++ ) { fonk_yaz(); Automatic variables A new a is formed for each enterence to the function. This is the default way.
Example: without using static void fonk_yaz(void) { int a = 0; printf("deger = %d\n", a); a++; void main() { int i; A new a variable is formed at each enterence to the function. The variable a is destroyed whenever we quit the function. for( i = 0 ; i < 3 ; i++ ) { fonk_yaz(); So, on the screen, we would see three 0 (zero) values.
void fonk_yaz(void) { static int a = 0; Example re-formed every time when entering the same function printf("deger = %d\n", a); a++; void main() { int i; On the screen, you see deger = 0 deger = 1 deger = 2 for( i = 0 ; i < 3 ; i++ ) { fonk_yaz();
void fonk_yaz(void) { static int a = 0; Example The variable a is formed at the beginning of the program, and its value is kept. printf("deger = %d\n", a); a++; void main() { int i; The variable is not destroyed when quitting the program. for( i = 0 ; i < 3 ; i++ ) { fonk_yaz();
Enumerated types variables that are formed by the keyword: enum
Enumerated types Gives you a chance to form your own type of variables. Its usage improves intelligibility of the program. For example, we may create a type to contain week days: enum Gunler { Pazartesi, Sali, Carsamba, Persembe, Cuma, Cumartesi, Pazar ;
Enumerated types We may make variables of the created type enum Gunler gun; switch(gun) { case Pazartesi: printf("pazartesi"); break; case Sali: printf("sali"); break;...
Enumerated Types Actually, each element in an enum type is a number list starting from 0. enum Gunler { Pazartesi, /* 0 */ Sali, /* 1 */ Carsamba, /* 2 */ Persembe, /* 3 */ Cuma, /* 4 */ Cumartesi, /* 5 */ Pazar /* 6 */ ;
Enumerated Types Since enum elements are numerical, they can be used in comparisons of if expressions. enum Gunler gun1, gun2; gun1 = (enum Gunler) 2; /* carsamba */ gun2 = "Pazartesi"; if(gun2 < gun1) { printf("gun2 daha onceki gun\n");
Scope How long do the variables stay valid?
Scope of Variables The variable scope is defined as the program segment in which the variable can be used. The variable name is an alias for the address of the variable in the memory. For example, if the variable is defined right after "void main {", then it is valid only in main(). It cannot be used anywhere else.
Scope of Variables If a variable is defined inside a block ( { and ), then it is valid until the end of block. If the variable is defined before all the functions, they are called global variables, and they are valid throughout the whole file.
Scope of Variables No two variables may have the same name if they are defined in the same scope. In different scopes, you can use variables with the same name. Since they correspond to different memory places, there will be no ambiguity. Yet, try to avoid using the same variable names under any circumstances.
Example - 1 x variable is not defined yet. Compile error!!! #include <stdio.h> void main ( ) { if ( x == 3 ) { float x = 4.5; x was only in the block, and now not defined any more... printf ( "blok içinde x=%f", x); printf( "bloktan sonra x=%d\n", x);
Example - 2 x variable is defined. OK!! #include <stdio.h> void main ( ) { int x = 3; Here, the nearestly defined one is valid. if ( x == 3 ) { float x = 4.5; printf ( "blok içinde x=%f", x); printf( bloktan sonra x=%d\n", x);
Scope of Variables In the previous example, there is an x variable defined right after main(). But in if block, there is another variable called x. Inside the block, that new variable will be valid, and the outer x is not valid. Since the two variables correspond to two different memory addresses, they will not be confused.
Would they? Run the program and see the following output: blok içinde x=4.5 bloktan sonra x=3