49
By/Mohamed Fawzy C-Programming Language 1 Day #3

C programming day#3

Embed Size (px)

Citation preview

By/Mohamed Fawzy

C-Programming Language

1 Day #3

2

Lecture Notes:

Set your phone to vibration mode.

Ask any time.

During labs feel free to check any materials or internet.

Agenda:

3

Strings.

User defined data types (Structures, Union, Enum).

C-scope rules.

Typedef.

Modularity.

C Header File.

C storage classes.

C preprocessor.

Compiling C code.

Agenda:

4

Strings.

User defined data types (Structures, Union, Enum).

C-scope rules.

Typedef.

Modularity.

C Header File.

C storage classes.

C preprocessor.

Compiling C code.

5

• C doesn't contain data type called String.

• String is array of characters with NULL terminator „\0‟.

EX#1: char first_name[5]={„m‟,‟o‟,‟h‟,‟a‟,‟m‟,‟e‟,‟d‟,‟\0‟};

Note:

In this case, the compiler isn't smart enough to figure we are constructing a string

And we must add NULL „\0‟ terminator.

EX#2: char first_name[8]=“Mohamed”;

Notes:

• In this case, the compiler realizes that we are constructing a string and

automatically adds the NULL terminator.

• The size of array is 8 not 7.

Strings.

6

EX#3: Char name[]=“mohamed fawzy”;

Note:

In this case, compiler deduces the size of array from the initial value

Strings. cont‟d

7

Printing Strings.

EX#1: char name[]=“Ahmed Osama”;

int i=0;

while(name[i] != „\0‟)

printf(“%c”,name[i++]);

Using Pointers: char name[]=“Ahmed Osama”;

Char *ptr;

Ptr=name;

while(*ptr != „\0‟)

printf(“%c”,*ptr++);

• Printing Using String Feature.

printf(“%s”,name);

Strings. cont‟d

• Strings may be printed manually.

8

Strings. cont‟d

Take Care !!!

char name[7]=“Mohamed”;

Here, the compiler deliberately excludes the NULL terminator and it become array

of characters not a String. (try to print it by previous methods).

In printing EX#1, if we did not use string (NULL terminator), printf would continue

Printing characters randomly from memory until by chance found a byte containing

zero.

EX#2:

char my_name[]=“Mohamed fawzy”;

printf(“%s”,my_name);

my_name[8]=„\0‟;

printf(“%s”,my_name);

9

Assigning to string.

• Strings may be initialized with “=” but not assigned to with “=”.

• The name of any array is a constant pointer to the zero element and cannot

be changes.

strcpy(destination,source);

EX#3: char who[]=“Mohamed”;

who=“Ahmed”; //not allowed

strcpy(who,”Ahmed”);

Note:

Don't forget to include string header file. #include <string.h>

Strings. cont‟d

10

Strings. cont‟d

Take Care !!!

char name[]=“Mohamed”;

strcpy(name, ” a really very large string indeed”);

This would overflow the array “name” and corrupt the memory Around it, this

would very likely cause a program to crash.

Solution

For solving this problem we would use another routine

strcpy(destination,source,size of destination);

EX#4: strcpy(name , ”large string”, size of (name));

11

Strings. cont‟d

Take Care !!!

The previous solution will cause another problem, because it will copy no of elements

Equal to size (it wouldn't copy NULL terminator).

Solution

For solving this problem we would add just one line of code.

destination [ sizeof (destination)-1]=„\0‟;

EX#5: strcpy(name , ”large string”, sizeof (who));

name[sizeof(name)-1]=„\0‟;

12

Strings. cont‟d

Pointers and strings. We can store strings by two methods:

• char str[]=“Hello”;

• char *strptr=“Hello”;

Notes:

• In second method we ask C compiler to store it in some location in memory and

assign the address of the string in a char pointer.

• The difference between the two forms is that in 1st method, we cannot assign

string to another but, in 2nd method we can assign a char pointer to another char

pointer.

EX#6: char str1[]=“Hello”;

char str2[10];

char *strptr=“Good Morning”;

char *q;

str2=str1; //giving an error

q=strptr; //no error

EX#7: char str1[]=“Hello”;

char *strptr=“Hello”;

Str1=“Bye”; //give an error

Strptr=“Bye”; //give no error

13

Strings. cont‟d

Accepting string from user.

char my_name [45];

printf(“Enter your name \n”);

scanf(“%s”,& my_name);

printf(“\n you entered %s”,my_name);

Take Care !!!

In previous example, if we entered “Mohamed Fawzy” it would print “Mohamed” only

Because scanf function stores characters until we press space.

Solutions

We can use fgets function. fgets included in <stdio.h>

fgets(string , size , stdin);

scanf(“%[^\n]s”,my_name);

Modify scanf function.

14

Strings. cont‟d

EX#8: char string [45];

printf(“Enter your name”);

fgets(string,45,stdin);

printf(“your name is %s”, string);

15

Strings. cont‟d

<string.h> functions

strcmp (str_1 , str_2);

This function take two strings as parameters from user, compare between them, it

return a value referred to result.

• If (str_1>str_2) it return 1

• If (str_1<str_2) it return -1

• If (str_1=str_2) it return 0

EX#9: int x;

x=strcmp(“A”,”a”); //”a” > ”A”

printf(“%d”,x);

Note:

The most common APP for this function is comparing password.

16 16

Strings. cont‟d

<string.h> functions

strcat (str_1 , str_2);

This function take two strings as parameters from user, concatenate them to

each other.

EX#9: char str_1[30]=“Mohamed”;

puts(strcat (str_1,”_Fawzy”));

Note:

puts function equivalent to printf(“\n”) printf(“%s\n”, puts(strcat (str_1,”_Fawzy”))

17 17 17

Strings. cont‟d

<string.h> functions

strlen (str_1);

This function take one strings as parameter from user, return its length (no of characters

excluding NULL terminator).

EX#9: int x;

char str_1[30]=“Mohamed”;

printf(“%d”, strlen (str_1));

Agenda:

18

Strings.

User defined data types (Structures, Union, Enum).

C-scope rules.

Typedef.

Modularity.

C Header File.

C storage classes.

C preprocessor.

Compiling C code.

19

User defined data types.

Structure. A structure is a collection of one or more variables with different data types

grouped together under a single name for convenient handling.

Variables in structures are called members and may have any type including

arrays or other structures.

Defining structure: struct <structure name>

{

<variable_1>;

<variable_2>;

...........

};

Note:

• structure type defining doesn't tell the compiler to reserve any space in memory,

it only define a template.

• Defining structure is written in program header (before main).

User defined data types.

Structure. cont‟d

Method#1: in defining structure.

EX#2: struct student_info

{

char name[10]; //10 bytes

int id; //2 bytes

char class; //1 byte

}ahmed , mohamed , osama;

Method#2:in main function.

EX#3: struct student_info

{

char name[10];

int id;

char class;

};

In main struct student_info ahmed,

mohamed;

Declaring a structure:

Note:

• Now, you reserved 13 byte for each declared variable.

• Structure elements stored in continuous memory locations.

21

EX#1:

struct student_info

{

char name[10];

int id;

char class;

} ;

name Id class

struct student_info ahmed , mohamed ;

name id class

Structure. cont‟d

Note:

• We can initialize structures instances with declaring it. struct student_info ahmed={“Ahmed”,20,3};

Accessing Structure Elements:

ahmed.name=“Ahmed”;

ahmed.id=5;

ahmed.class=2;

mohamed.name=“Mohamed”;

mohamed.id=10;

mohamed.class=1;

name id class

Ahmed 5 2

Mohamed 10 1

Structure. cont‟d

Structure. cont‟d

Array of structure.

EX#: struct student_info arr[5];

Note:

• Here, struct student_info is the data type.

• In very large programs they are usually put in a separate header file,

and the file included in main program.

Structure. cont‟d

Structures and pointers.

struct rectangle

{

int length;

int width;

};

int main()

{

struct rectangle rect_1;

struct rectangle *ptr;

Ptr=&rect_1;

Ptr->length=5;

Ptr->widdth=10;

}

Note:

• Ptr->length is equivalent to (*ptr).length

Take Care !!!

• *ptr.length not equivalent to (*ptr).length.

• *ptr.length =*(ptr.length) because “.” has

higher precedence than “*”.

Structure. cont‟d

Passing structure by value:

struct rectangle

{

int length;

int width;

};

int area(struct rectangle rect)

{

return (rect.lengh*rect.width);

}

int main()

{

struct rectangle rect_1;

int rect_area;

rect_1.length=10;

rect_1.width=5;

rect_area=area(rect_1);

printf(“%d”,rect_area);

}

Structure. cont‟d

Passing structure by reference:

struct rectangle

{

int length;

int width;

};

int area(struct rectangle *rectptr)

{

return (rectptr->lengh*rectptr->width);

}

int main()

{

struct rectangle rect_1;

struct rectangle *ptr;

int rect_area;

ptr->length=10;

ptr->width=5;

rect_area=area(&rect_1);

printf(“%d”,rect_area);

}

Structure. cont‟d

Passing structure by reference: cont‟d

Notes:

• Passing structures by reference (using pointers) is better than passing

by value;

• Passing by value place struct in stack and structure may include arrays

or other structures.(may cause stack overflow error).

• It is better to use constant pointer to structure. (why) const struct student_info *ptr.

const int *ptr; //pointer to constant integer

p++; //allowed

*p=15; //not allowed

//the value at the end of pointer cannot be changed

This helps you to avoid a common mistake

If (ptr->length = 0)

• The values of a structure variables can be assigned to another structure

variable of the same type using assignment operator. ahmed=mohamed;

Agenda:

28

Strings.

User defined data types (Structures, Union, Enum).

C-scope rules.

Typedef.

Modularity.

C Header File.

C storage classes.

C preprocessor.

Compiling C code.

C-scope rules.

• A scope in any programming is a region of the program where a defined variable

can have its existence and beyond that variable can not be accessed. There are

three places where variables can be declared in C programming language:

1) Inside a function or a block which is called local variables.

2) Outside of all functions which is called global variables.

3) In the definition of function parameters which is called formal parameters.

Agenda:

30

Strings.

User defined data types (Structures, Union, Enum).

C-scope rules.

Typedef.

Modularity.

C Header File.

C storage classes.

C preprocessor.

Compiling C code.

Typedef

you can use to give a type a new name.

EX#: typedef unsigned char BYTE;

BYTE b1,b2;

you can use typedef to give a name to user defined data type as well.

EX#: typedef struct book

{

char title[50];

char author[50];

char subject[100];

int book_id;

} Book;

Book b1,b2;

32

• The typedef is limited to giving symbolic names to types only where as

#define can be used to define alias for values as well, like you can define

1 as ONE etc.

• The typedef interpretation is performed by the compiler where as

#define statements are processed by the pre-processor.

Typedef Vs. #define

Agenda:

33

Strings.

User defined data types (Structures, Union, Enum).

C-scope rules.

Typedef.

Modularity.

C Header File.

C storage classes.

C preprocessor.

Compiling C code.

Modularity.

file.h

file.c

Agenda:

35

Strings.

User defined data types (Structures, Union, Enum).

C-scope rules.

Typedef.

Modularity.

C Header File.

C storage classes.

C preprocessor.

Compiling C code.

C Header File.

• A header file is a file with extension .h which contains C function declarations and

macro definitions and to be shared between several source files. There are two

types of header files: the files that the programmer writes and the files that come

with your compiler.

• You request the use of a header file in your program by including it, with the C

preprocessing directive #include like you have seen inclusion of stdio.h header

file, which comes along with your compiler.

• A simple practice in C or C++ programs is that we keep all the constants, macros,

system wide global variables, and function prototypes in header files and include

that header file wherever it is required.

#include <file.h>

#include “file.h”

Agenda:

37

Strings.

User defined data types (Structures, Union, Enum).

C-scope rules.

Typedef.

Modularity.

C Header File.

C storage classes.

C preprocessor.

Compiling C code.

C storage classes.

• A storage class defines the scope (visibility) and life-time of variables and/or

functions within a C Program. These specifiers precede the type that they

modify. There are the following storage classes, which can be used in a C

Program:

1. auto

2. register

3. static

4. extern

The auto Storage Class

EX: int student_no;

auto int student no;

C storage classes. cont‟d

The register Storage Class The register storage class is used to define local variables that should be stored

in a register instead of RAM. This means that the variable has a maximum size

equal to the register size (usually one word) and can't have the unary '&' operator

applied to it (as it does not have a memory location).

EX: register int student no;

Note:

defining 'register' does not mean that the variable will be stored in a

register. It means that it MIGHT be stored in a register depending on

hardware and implementation restrictions.

The auto storage class is the default storage class for all local variables.

C storage classes. cont‟d

The static Storage Class

With Local variables:

The static storage class instructs the compiler to keep a local variable in existence

during the life-time of the program instead of creating and destroying it each time it

comes into and goes out of scope.

With Global variables:

it causes that variable's scope to be restricted to the file in which it is declared.

C storage classes. cont‟d

The extern Storage Class

When you have multiple files and you define a global variable or function, which

will be used in other files also, then extern will be used in another file to give

reference of defined variable or function.

Agenda:

43

Strings.

User defined data types (Structures, Union, Enum).

C-scope rules.

Typedef.

Modularity.

C Header File.

C storage classes.

C preprocessor.

Compiling C code.

C - Preprocessors

Agenda:

45

Strings.

User defined data types (Structures, Union, Enum).

C-scope rules.

Typedef.

Modularity.

C Header File.

C storage classes.

C preprocessor.

Compiling C code.

Compiling C Program.

47

Hands ON

Email: [email protected]

Phone: 01006032792

Facebook: [email protected]

Contact me:

48

49