0% found this document useful (0 votes)
28 views33 pages

CP Notes Unit 3 br23

The document provides an introduction to programming concepts focusing on arrays and pointers. It covers the definitions, initialization, declaration, and accessing of one-dimensional and two-dimensional arrays, as well as dynamic memory management and pointer manipulation. Additionally, it includes examples and syntax for array operations and initialization methods in C programming.

Uploaded by

stalinch509
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
28 views33 pages

CP Notes Unit 3 br23

The document provides an introduction to programming concepts focusing on arrays and pointers. It covers the definitions, initialization, declaration, and accessing of one-dimensional and two-dimensional arrays, as well as dynamic memory management and pointer manipulation. Additionally, it includes examples and syntax for array operations and initialization methods in C programming.

Uploaded by

stalinch509
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 33
UNIT INTRODUCTION TO PROGRAMMING —[-BTECI I-SEM BR23 UNIT IN (Arrays & Pointers) Arrays: Arrays definition and indexing, Types of Arrays One-Dimensional Arrays: Initialization, declaration and accessing, input and output of array Two-Dimensional Arrays: Initialization, declaration, accessing, input and output of array Case Study: Matrices, Larger Dimensional Arrays Pointers: Concept of a pointer, Initialization of pointer variables and access, Pointer dereferencing and address operators, array manipulation using pointers,Dynamic Memory Management functions,pointers to pointers, command line arguments L.Define an Array?Explain the One dimensional array Initialization, declaration sAccessing, input/output in array Arrays definition and indexing, Types of Arrays: Array: Array is a collection of variables belongings to the same data type. You can store group of data of same data type in an array.It is called as Heterogeneous. + Array might be belonging to any of the data types ‘+ Array size must be a constant value, + Always, Contiguous (adjacent) memory locations are used to store array clements in memory. + Itis a best practice to initialize an array to zero or null while declaring, if we don’t assign any values to array. © inta{l0); — // integer array + char b[10]; // character array i.e. string ‘Types of Arrays: There are 2 types of arrays. They are, 1.One dimensional array 2.Two dimensional array 3.Multi dimensional array(Large Dimensional Array) Syntax: data-type arr_namefarray_size]; lization [Accessing array [Array declaration (Syntax: Idata_type arr_name [arr_size];)/Datatype Arr-name [size]={valuel, value2 .}5arr_name{index]; jt lint age [5]; lint age(5}=(0, 1, 2, 3, 4, 5); ljage[1]; /*1 is accessed le lage[2]; /*2 is accessed fage[O}; /*0 is accessed | i —_— Prepared By B.Narasimha Rao (BNR), Associate Professor, CSE Dept. ,BVCEC, Odalareu Page ssed* {char str[10]={*C’,‘P’}; (or) | ; Ichar str{0] = ‘C’: Iste[0];_/*HL is accessed* cchar str[10];, ichar str[1 Isur[L]; (a is ace BR23 UNIT-IL INTRODUCTION TO PROGRAMMING —I-BTECH 1-SE! Declaration of an One Dimensional Array:During declaration, the size of the array has to be specified. The size used during declaration of the array informs the compiler to allocate and reserve the specified memory locations. Syntax:- data_type array_name| n]; | where, n is the number of data items (or) index(or) dimension, 0 to (n-1) is the range of array. Ex: int a5}; float x[10]; char ch{9]; Initialization of Arrays: The different types of initializing arrays: 1. At Compile time: , (i) Initializing all specified memory locations. (ii) Partial array initialization Gi) Initialization without size. (iv) String initialization 2. At Run Time : 1. Compile Time Initialization: We can initialize the elements of arrays in the same way as the ordinary variables when they are declared. The general form of initialization of arrays is Data_type Array-name|size]={ list of values/elements}; : (i Initializing all specified memory locations:~ Arrays can be initialized at the time of declaration when their initial values are known in advance. Array elements can be initialized with data items of type int, char etc. Ex:- int a[5]=(10,15,1,3,20}; Accessing One Dimensional Array: During compilation, 5 contiguous memory locations are reserved by the compiler for the variable a and all these locations are initialized as shown in figure Ex:- int a[5]={10,15,1,3,20}; a0) aft] af2]__af3]. als) 10 13 1 3 20 1000 1002 1004 1005 1008 ‘Above array can be initialized as accessing given below art{0) / Accessing each variable arr{1] = 15; arr{2] = 1; 9,2,4,5,6); //error: no. of initial vales are more than the size of array. Partial array initialization:- Partial array initialization is possible in c language. If the number of values to be initialized is less than the size of the array, then the elements will be initialized to zero automatically. Ex:~ int a[5}=(10,15}; Even though compiler allocates 5 memory locations, using this declaration statement; the compiler initializes first two locations with 10 and 15, the next set of memory locations are automatically initialized to 0's by compiler as shown in figure. Initiali with all zeros:~ (0) afl] a) a ais) 10 | 15 0 0 0 1000 1002 1004) 1006 1008. Ex:- int a[5|={0}; a0} aft) af) af3) 0 of 0 0 1000 1002 1004 1006 larasimha Rao (BNR), Associat Prepared By B. UNITAL INTRODUCTION TO PROGRAMMING —I-BTECH 1-SEM BR23 ii) Initialization without size:- Consider the declaration along with the initialization. Ex char bll((CO'yMYyPY'U'TYER'}; In this declaration, even though we have not specified exact number of elements to be used in array b, the array size will be set of the total number of initial values specified. So, the array size will be set to 8 automatically. The array b is initialized as shown in figure. bp] bia) bis] of) bi) c 7 Py UTTt TER 0 Yo0o 1001 1002 1003 1004 1005 1006 1007 1008 Fig: Initialization without size Ex- int ch{]}={1,0,3,5} // array size is 4 i) Array initialization with a string: - declaration with string initialization. Ex:- char b[]="COMPUTER"; The array b is initialized as shown in figure. bio] bi] b2]__bg) bys] bys]__bg6]___ c 3° M Pr uU T E R 1000 1001 1002, 1003 1004 1005 1006 1007 Fig: Array Initialized with a String Even though the string "COMPUTER’ contains 8 characters, because it is a string, it always ends with null character. So, the array size is 9 bytes (i. string length 1 byte for null character).Ex:- char b[9]="COMPUTER"; Mcorrect char b[8]="COMPUTER"; I wrong 2.Run Time Initialization:An array can be explicitly initialized at run time. This approach is usually applied for initializing large arrays. Ex 1:-scans can used to initialize array. intx(3]; scans("%d%d%d" Bex[0},Sex{1],x12]) ‘Above statements will initialize array elements with values entered through key board. 0; / Accessing each variable U/ Accessing each variable scans(“%d ”,&arti); } arr{0}= 10; ar{1]=15; arf] =; avr{3] = 3; arr[4] = 20; al afl 4 Blas 3 x 1002-1004 «10051008 — Tropared By BNarasimha ao (BNR), Associate Professor, CSE Dept. BVCEC, Odlalareu Pay) UNIT-In INTRODUCTION TO PROGRAMMING —I-BTECH [-SEM — BR23 x3 for(i=0;i<100;i=i+1) { ii<50) sumf[i}=0.0; else sum[i}=1.0; ‘The first 50 elements of the array sum are initialized to 0 while the remaining 50 are initialized to 1.0 at run time, Example program for one dimensional array Hincludesstdio.h> main() { inti; int a(S] = {10,20,30,40,50); // declar and Initial all array elements to 0, use int ar[5}={0}; 1* Above array can be initialized as below also ar[0]= 10; " art{1]=20; am{2]=30; arr{3]=40; am[4]= 50; */ for (i=0;i<5;i+) {// Accessing each variable pratt Value of arr[%al] is %d \n”, i, ar[i); } Output: [value of arx{0} is 10] value of arr{1} is 20 nl[Array declaration [Array initialization [Accessing array Syntax: (data type art_name(2][2) =| 1 ! [Datatype Arr-name {num_of rows][num_of col]; |{{0,0},(0,1}x(1,0},{In1}};_[@—namelinden| jarr (0) [0] = 1; 2 |lExample:c int ar{2](2); int ar(2}(2)= (1,2,3,4); [8 a 3 I larr [1] (1] = 4: | How can we declare and initialize 2D arrays:An array consisting of two subscripts is known as two-dimensional array. These are often known as array of the array. In two dimensional arrays the array is divided into rows and columns. Declaration of an Two Dimensional Array: data_type array_name|number_of_rows_size][number_of_column_size| int arr{3)(3]; where first index value shows the number of the rows and second index value shows the ee Prepared By B.Narasimha Rao (BNR), Associate Professor, CSE Dept. BVCEC, Odalareu Page + L-SEM — BR23 uU ee NUT INTRODUCTION TO PROGRAMMING 1-BIECH ftmber of the columns in the array. }OW the memory is allocated for a 2D array: These are stored in the memory as * Row-Major order Implementation In Row. Column-Major order Implementation in Row-Major Implementation of the arrays, the arrays arc stored in the memory In terms of the row design, ie. first the first row of the array is stored in the memory then second and so on. Suppose we have an array named arr having 3 rows and 3 columns then it can be stored in the memory in the following manner : int _ar(3)(3). Where first index value shows the number of the rows and second index value shows the no. of the columns in the array. 1/ declaring and Init int arr{2}(2) = (10,20,30,40}; 7 Above array can be initialized as below also arr{0](0) = 10; !/ Initializing array arr{0}{1) = 20; arr{1}[0] = 30; arr{1][1]= 4 . At Compile time: Thus an array of 3°3 can be declared as follows : an(3}13) = { | “/ memory with row major implementation as follows : 6 7 | 0 implementationof the arrays, the arrays are stored in the memory in the team of the column design, i. the first column of the array 1s stored in the memory then the second and so on. By taking above eg. we can show it as follows : Int arr{3[3) = (12,35 4,56, sory with column major implementation as follows SEM BR23 UNIT-I INTRODUCTION TO PROGRAMMING —I-BTECH SEM CPP PE EET Two-dimensional arrays of variable length: | | 4 An array consisting oriwo subscripts is known as two-dimensional array ee ie known as array of the array. In two dimensional arrays the array is divided into Potts at columns,, These are well suited to handle the table of data, In 2-D array we can declare 4 array as i Declaration:-Syntax: data_type array_name|row_size|{column_size|; Ex: int arr{3][3) ; These are stored in the memory as given below. farr{0](0] am[O)[1] — farr{0)[2) ire oflen and jerr{1}[0] for 1)(1] fare 1)(2] jerr{2][0] wm{2}(1)—farr{2](2] Like the one-dimensional arrays, two-dimensional arrays may be initialized by following their declaration with a list of initial values enclosed in braces. Ex: int a[2][3]={0,0,0,1,1,1}; initializes the elements of the first row to zero and the second row to one. The initialization is done row by row. The above statement can also be written as by surrounding the elements of each row by braces int a[2][3] = {{ 0,0,0},{1,1,1}}5 -We can also initialize a two-dimensional array in the form ofa matrix as shown below int a[2)[3]}={ {0,0,0}, {1,11} k When the array is completely initialized with all values, explicitly we need not specify the size of the first dimension, int af]3}-( {0,2,3}, {2,1,2} k If the values are missing in an initializer, they are automatically set to zero. Ex: int a[2][3]={{1,1}, ne Will initialize the first two elements of the first row to one, the first element of the second row to two and all other elements to zero. 2.Run Time Initialization: An array can be explicitly initialized at run time. This approach is usually applied for initializing large arrays of row and column.To initialize values for variable length arrays we can use scans statement and loop constr Prepared By B.Narasimha Rao (BNR), Associate Professor, CSE Dept. BVCEC, Oct cul Page 6 UNIT-I INTRODUCTION TO PROGRAMMING — I-BTECIT SEM Ex: for (i=0 ; i<3; i++) { for(j=0;j<3;j+-1) seans(“%d",&arr{i]fj } for (i=0 ; i<3; i++) ¢ { for(j=0;j<3;j++) scans(“%d",&antfi)[j } Example program for two dimensional array Hinelude main() int ij; / declaring and Initializing array int arr{2][2] = {10,20,30,40}; /* Above array can be initialized as below also arr{0][0] = 10; // Initializing array arr(0][1] = 20; arr{1]{0] = 30; arr[1][1] = 40; */ for (i-0;i<2;i++) { for (j= 0;j<2,5+4) printf{(“value of arr[%d] [%d] : %d\n”,i,j,arr[i][j)); \\ Accessing variables value of arr[ 1] [1] is 40] /*MATRIX MULTIPLICATION*/ Hinelude void main() { int af} 0][10},b(10}{10},c{ 10]{10}; Prepared By B.Narasimha Rao (BNR), BR23 UNIT-IIT INTRODUCTION TO PROGRAMMING = [-BTECH I-SEM — BR23 int ij,km,n,p.q; Print{("\ Enter the size of Matrix A:"); Scans("%d%d", &m, én); Printf("\ Enter the size of Matrix Seans("%d%d", &p,&q); pa {_ print{("Matrix Multiplication not possible."); exit(); } printf" Enter the Matrix A values:\n"); a Met a ("Enter the Matrix B values:\ sispiit+) ‘i main) { int ij; “declaring and Initializing array int arr[2](2) = (10,20,30,40}; ‘* Above array can be initialized as below also arr{0}{0](0] = 10; // Initializing array arr{0)(0}[1] = 20; an[1][0}{0] = 30; arr ]E1][0] = 40; #7 for (i=0;i<2si+-+) { for G=0;j<25j+4) { for (k=0;k<2;k+4) {// Accessing variables pene ale of arr{(%d] [%d] : %od\n",j,arr(iJL]CK)); n for Mulli dimensional array Pointer(Concept of a pointers Pointers are one of the core components of the C programming language. A pointer can be used to store the memory address of other variables, functions, or even other pointers. The use of pointers allows low-level memory access, dynamic memory allocation, and many other functionality in C. Syntax of C Pointers ‘The syntax of pointers is similar to the variable declaration in C, but we use the ( * ) dereferencing operator in the pointer declaration, datatype * ptr; Ex; int “ptr; where © ptris the name of the pointer. «datatype is the type of data it is pointing to. The above syntax is used to define a pointer to a variable. We can also define pointers to functions, structures, etc. Features and Uses of Pointers in C ‘The C pointer is a very powerful tool that is widely used in C pro various useful operations, It is used to achieve the following functionalities in C. 1, Pass Arguments by Referens to pertorm Prepared By B.Narasimha Rao (BNR), Associate Profess' Page UNIT-I INTRODUCTION TO PROGRAMMING 1-BTECHE SEM. BR2s 2. Accessing Array Elements 3. Return Multiple Values from Function 4. Dynamic Memory Allocation 5, Implementing Data Structures 6. In System-Level Programming where memory addresses are useful. 7. In locating the exact value at some memory location. 8. To avoid compiler confusion for the same variable name. 9. Touse in Control Tables. Advantages of Pointers Following are the major advantages of pointers in C: + Pointers are used for dynamic memory allocation and deallocation. © An Array or a structure can be accessed efficiently with pointers + Pointers are useful for accessing memory locations + Pointers are used to form complex data structures such as linked lists, graphs, ees + Pointers reduce the length of the program and its execution time as well. Disadvantages of Pointers Pointers are vulnerable to errors and have following disadvantages: . Memory corruption can occur if an incorrect value is provided to pointers. . Pointers are a little bit complex to understand. . Pointers are majorly responsible for memory leaks inc. . Pointers are comparatively slower than variables in. + Uninitialized pointers might cause a segmentation fault. Uses in Pointers: ‘The use of pointers in C can be divided into three steps: 1 Pointer Declaration 2. Pointer Initialization 3. Pointer Dereferencing 1. Pointer Declaration: In pointer declaration, we only declare the pointer but do not initialize it. To declare a pointer, we use the (*) dereference operator before its name, Example: int *ptr; 2.Pointer I itialization of pointer variables and access): Pointer initialization is the process where we assign some initial value to the pointer variable, We generally use the ( & ) address of operator to get the memory address of a variable and then store it in the pointer variable. ‘Access the array elements using pointers int an{5) = {100, 200, 300, 400, 500}; int “pur = arr; Where ptr is an integer pointer which hokds the address of the first element. Le &arr[O] ptr + 1 points the address of second variable. ic &arr{] Similarly, ptr +2 hols the address of the third element of the array. ie. &are[2] Printing each array elements address and value ‘Prepared By B.Narasimha Rao (BNR), Associate Profess Odalare Page UL Dept. ,BVCE >M —BR23 UNIT-II INTRODUCTION TO PROGRAMMING —--BTECIE F dinclude int main() { int arr{$] = (100, 200, 300, 400, 500}, i; int *ptr = arr; J Address ptrti ‘Nalue stored at the address *(ptrti) for(i i< S;it+) print{("Sarr[%d] = %p\t arr{%d] = %d\n" piri, *(ptr+i)); return 0; } Example int var = 10; int * ptr; ptr = &var; We can also declare and initialize the pointer in a single step. This method is called pointer definition as the pointer is declared and initialized at the same time. Example int *ptr = &var; Note: It is recommended that the pointers should always be initialized to some value before starting using it. Otherwise, it may lead to number of errors. 3. Pointer Dereferencing and address operators: Dereferencing a pointer is the process of accessing the value stored in the memory address specified in the pointer. We use the same (* ) dereferencing operator that we used in the pointer declaration. void main() { int var = 10; 1/ declare pointer variable int* ptr; 1/ note that data type of ptr and var must be same pir = &var; //assign the address of a variable to a pointer printf("Value at ptr=%p \n", ptt); printf("Value at var printf("Value at *ptr = %d \n", *ptr); Prepared By B.Narasimha Rao (BNR), Associ eccHt ESI } INTRODUCTION TO PROGRAMMING L-BTECH SEM BR? au Output: Value at ptr = 0x7: {11 038675¢ Value at var = 10 Value at *ptr= 10 Dereference. is used the pointer variable (0 get together with the & reference operator), int myAge=24; _// Variable declaration in® pir= &myAge; // Pointer declaration Tr Reference: Outpt the memory adress of myAge wit the pointer (Ox7fe5367¢044) print{("%p\n", ptt); ie erteenee- Output the value of myAge withthe poiter (24) printf("%d\n", *pts)s the memory address of a variable (used Types of Pointers in C: Pointers in C can be classified into many different types based on the parameter on which Points Jofning their types. If we consider the tyPe of variable stored in the memory Tocation pointed by the pointer, then the pointers can De classified into the following tyPes: 1 Array Pointer( Array Manipulation using Pointerl: Pointers and Array are closely related to each other. Eve its first element. They are also known as Pointe array using the given syntax. Syntax: char *ptr = &array name; ex: char name(3]="bnr”; char *p=&name(0]; iidefine MAX 10 int main() { int af MAX]; int D(MAX]; inti for(i=0; iC MAX; i++) afij-i ba; retum 0; } emer this code and try to compile it, You will ind that C wil nat compile it. IF you want 0 copy a into b, the statement a=b; therefore does not work. #define MAX 10 void main() { int af MAX]; inti; int *p; pra; for(i=0; iC MAX; i+) alil=i; nt ("Y%odin", *p); nthe array name is the pointer tO | We can create a pointer to an ha Rao (BNR), Assoc ITEC -SE BR23 UNIT-IL INTRODUCTION TO PROGRAMMING — EBTECIT SEM BR 1 ‘The statement pea; works because a is a pointer. Technically, a points to the address of the Oth element of the actual array. This clement is an integer, so a is a pointer me single int er Therefore, declaring p as a pointer to an integer and setting it equal to a works y to say exactly the same thing would be to replace p=a; with p=&al0];. Since a contains the address of a[0}, a and &a[0] mean the same thing. / Now that p is pointing at the Oth element of a, you can do some rather strange things wih i The a variable is a permanent pointer and can not be changed, but p is not sul Ha io - restrictions. C actually encourages you to move it around using pointer arithmetic Pa example, if you say p++s, the compiler knows that p points to an integer, SO this statement increments p the appropriate number of bytes to move it to the next element of tl a Ifp were pointing to an array of 100-byte-long structures, p++; would move p over by 100 bytes. C takes care of the details of element size. for (i=0; is MAX; i++) { *q=*p ‘And you can further abbreviate it to: for (p=a,q=b,i=0; i void main () { inta=10; int *p; int **pps ir pointer pis pointing to the address of a P p=; / pointer pp is a double pointer otating to the address of pointer p print(‘address of a: Yoxin",p); 1 Address ofa will be printed print(taddress of p: %x\0",pP); 11 Address of p will be printed Print(value stored a p: Yéd\n'tp) value stored at address contain by p printf("value stored at pp: %d\n",**Pp); Pr value stored atthe address contained by the pointer stoyred at pp } Output address of a: 42628734 address of p: 42628738 value stored at p: 10 value stored at As you can see inthe above figure, p2 contains the address of p (M2), ana pantans the address of number variable (nr). Hinclude main() red By B.Narasimha Rao (BNR), Asso« INIT UNIT-M INTRODUCTION TO PROGRAMMING — -BTECH -SEM — BR23 { int number=5o; int “py/pointer to int int **p2i//pointer to pointer number://stores the address of number variable P2=&p; Printft"Address of number variable is %x \n" number); Printf{"Address of p variable is %x \n",p); Printf(" Value of *p variable is %d \n".*p); Print{("Address of p2 variable is %x \n" p2); primate of **p2 variable is %d \n",*p); Output Address of number variable is fff4 Address of p variable is fff Value of *p variable is 50 Address of p2 variable is fff2 Value of **p variable is 50 S. NULL Pointer: The Null Pointers are those pointers that do not point to any memory location. They can be created by assigning a NULL value to the pointer. A pointer of any type can be assigned the NULL value. Syntax: data_type *pointer_name=NULL; ex: pointer_name = NULL It is said to be good practice to assign NULL to the pointers currently not in use. Uses of NULL Pointer in C Following are some most common uses of the NULL pointer in C: 1.To initialize a pointer variable when that pointer variable hasn't been assigned any valid memory address yet. 2.To check for a mull pointer before accessing any pointer variable. By doing so, we can perform error handling in pointer-related code, e.g., dereference a pointer variable only it it’s not NULL. 3.To pass a null pointer to a function argument when we don’t want to pass any valid memory address. 4.A NULL pointer is used in data structures like trees, linked lists, etc. to indicate the end. Cheek if the pointer is NULL It is a valid operation in pointer arithmetic to check whether the pointer is NULL. We just have to use isequal to operator ( ==) as shown below: ptr== NULL; The above equation will be true if the pointer is NULL, otherwise, it will be false. Example 1: C Program to avoid segmentation fault while accessi pointer using NULL pointer wg the value of 1/ C NULL pointer demonstration nha Rao (BNR), As UNIT-I INTRODUCTION TO PROGRAMMING —I-BTECIT [SEM BR24 Hinclude main() {_1/ declaring null pointer int* ptr = NULL: 1/ derefencing only if the pointer have any value if (ptr = NULL) { : {{("Pointer does not point to anything"): else { printf("Value pointed by pointer: %d”, *ptr); } } Output: Pointer does not point to anything By specifically mentioning the NULL pointer, the C standard gives mechanism using which a C programmer can check whether a given pointer is legitimate or not 6.Void Pointer: Fhe Void pointers in C are the pointers of type void. It means that they do not have any ascosiated data type. They are also called generic pointers as they can point fo any tyP© and can be typecasted to any type. Syntax: void* pointer_name; — ex: void *ptr; One of the main properties of void pointers is that they cannot be dereferenced. int i=9; // integer variable initialization. int *p; _// integer pointer declaration. float *fp; _// floating pointer declaration. void *ptr; // void pointer declaration. // incorrect. / incorrect 1/ correct II correct ptr=&i; —// correct 7. Wild Pointers: The Wild Pointers are pointers that have not been initialized with something yet. These types of pointers can cause problems in our programs can eventually cause them to crash. Example: int *ptr; char *str; 8. Constant Pointers: In constant pointers, the memory address stored inside the pointer is constant and cannot be modified once it is defined. It will always point to the same memory address. Syntax: — data_type * const pointer_name; ex: int *const ptr, #include int main() { int int b=2; int *const ptr; ha Rao (BNR), Associate Pr rei ES 23 UNIT-1 INTRODUCTION TO PROGRAMMING = -BTECIT ESEM BR: pir=&b; Print"Value of ptr is :%d",*ptr); return 0; } Heorror In the above output, we can observe that the above code produces the error “assignment of read-only variable 'ptr'". It means that the valuc of the variable ‘ptr’ which ‘pir’ is holding eannot be changed. In the above code, we are changing the value of ‘pr’ from éa to &b, which is not possible with constant pointers. Therefore, we can say that the constant pointer, which points to some variable, cannot point to another variable, © We declare two variables, ie., a and b with values I and 2, respectively. We declare a constant pointer. First, we assign the address of variable 'a' to the pointer ‘ptr’ ‘Then, we assign the address of variable ‘b' to the pointer ‘ptr’. Lastly, we try to print the value of the variable pointed by the ‘ptr’ ‘ointer to Constan: . The pointers pointing to a constant value that cannot be modified are called pointers to a constant. Here we can only access the data pointed by the pointer, but cannot modify it. Although, we can change the address stored in the pointer to constant. Syntax: const data_type * pointer_name; _ex: const int* ptr; Hinclude int main) 20000 ptr=&e printf("Value of ptr is :%u" ptr); return 0; We declare two variables, i.e., a and b with the values 100 and 200 respectively. We declare a pointer to constant. First, we assign the address of variable ‘a’ to the pointer ‘ptr. Then, we assign the address of variable 'b’ to the pointer ‘ptr’. co Lastly, we try to print the value of ‘ptr’. Output ooo ot Seer reer) The above code runs successfully, and it shows the value of ptr’ in the output. Other Types of Pointers in C: There are also the following types of pointers available to use in C apart from those specified above: Dangling pointer: A pointer pointing to a memory location that has been deleted (or treed) is called a dangling pointer. File Pointer: he pointer to a FILE data type is called a stream pointer or a file pointer. CSE Dept. BVCEC, Odalarew Page Li INTRODUCTION 10 PROGRAMMING = I-BTECH [SEM — BR23 The size of the pointers in C is equal for every pointer type. The size of the pointer docs not depend on the type it is pointing to. It only depends on the operating system and CPU architecture. The size of pointers in C is . 8 bytes for a 64-bit System + 4 bytes for a 32-bit System The reason for the same size is that the pointers store the memory addresses, no matter what type they are. As the space required to store the addresses of the different memory locations is the same, the memory required by one pointer type will be equal to the memory required by other pointer types. int main) { dummy variables definitions int a= 10; char c=" struct str x; 1/ pointer definitions of different types int* ptr_int = &a; char* ptr_char struct str* ptr_str void (*ptr_func)(int, void* ptr_vn= NULL; printing sizes printf("Size of Integer Pointer \t:t%d bytes\n", sizeof{ptr_int)); print{("Size of Character Pointer\t:\t%d bytes\n" sizeof(ptr_char)); printf("Size of Structure Pointerit:\t%d bytesin", sizeof{ptr_str)); print{("Size of Function Pointer\:\t%d bytes\n", sizeof{(ptr_func)); printf("Size of NULL Void Pointer\t:\t%d bytes" sizeof{(ptr_vn)); return 0; ) Output Size of Integer Pointer: 8 bytes Size of Character Pointer : 8 bytes Size of Structure Pointer: 8 bytes Size of Function Pointer : 8 bytes Size of NULL Void Pointer: 8 bytes ‘As we can see, no matter what the type of pointer itis, the size of each and every pointer is the same.Now, one may wonder that if the size of all the pointers is the same, then why do we need to declare the pointer type in the declaration? The type declaration is needed in the pointer for dereferencing and pointer arithmetic purposes. &func; C Pointer Arithm The Pointer Arithmetic refers to the legal or valid arithmetic operations that can be performed on a pointer. It is slightly different from the ones that we generally use for mathematical calculations as only a limited set of operations can be performed on pointers These operations include: + Increment in a Pointer + Decrement in a Pointer isimha Rao (BNR), Associate Professor, UNIT-I INTRODUCTION TO PROGRAMMING —I-E EM BR23 + Addition of integer to a pointer + Subtraction of integer to a pointer . Subtracting two pointers of the same type * Comparison of pointers of the same type. + Assignment of pointers of the same type. main) {Declare an array int v[3] = { 10, 100, 200 }; // Declare pointer variable int* ptr; // Assign the address of v(0] to ptr ptr=v; for (int i=0; 1<3; i++) { // print value at address which is stored in ptr Printf("Value of *ptr = Yd\n", *ptr); // print value of ptr Printf("Value of ptr = %ep\n\n", ptr); // Increment pointer ptr by 1 pirt+; } ) Output Value of *ptr = 10 Value of ptr = Ox7ffe8ba7ec50 Value of *ptr = 100 Value of ptr = Ox7ffe8ba7ecS4 Value of *pt Value of ptr = Ox7ffe8ba7ec58 Increment/Decrement of a Pointer: Increment: It is a condition that also comes under addition. When a pointer is incremented, it actually increments by the number equal to the size of the data type for which it is a pointer. For Example If an integer pointer that stores address 1000 is incremented, then it will increment by 4(size of an int), and the new address will point to 1004. While if a float type pointer is incremented then it will increment by 4(size of a float) and the new address will be 1004, Decrement: It is a condition that also comes under subtraction. When a pointer is decremented, it actually decrements by the number equal to the size of the data type for which itis a pointer. For Example If an integer pointer that stores address 1000 is decremented, then it will decrement by 4(size of an int), and the new address will point to 996. While if'a tloat type pointer is decremented then it will decrement by 4(size of « float) and the new address will be 996. Odalavets P Prepared By B.Narasimha Rao (BNR), Associate Professor, UNIT-HIL INTRODUCTION TO PROGRAMMING —I-BIFCH FST M BR2S Note: It is assumed here that the architecture is 64 sized accordingly. For example, integer is of 4 bytes. ‘and all the data types are include ‘ pointer increment and decrement ‘pointers are incremented and decremented by the size of the data type they point to int main() int a int *p = &a; printf("p = %u\n", p); // p = 6422288 pH printi("p++ = %ul\n", p); //p++ = 6422292 +4 // 4 bytes printf("p--=%uln", p); /p--= 6422288 -4 i! restored to original value float b = 22.22; float *q = & printf("q = You\n", q); //q = 6422284 ahs printt("q+t = Youn", q); a+ = 6422288 +4 14 bytes Ca printf("q--= %uln’, a); /q--= 6422284 -4 I! restored to original value ic printf("r = Yuin", 1); Mr = 6422283, rH prini(’r++=%uln", 1); lirt+ = 6422284 +1 I L byte Bs printi('r~=%uln’, 1); = 6422283 1 I/ restored to original value return 0; ) C Pointers and Arra' Tn C programming language, pointers and arrays are closely related. An array name acts like @ pointer constant. The value of this pointer constant is the address of the first clement. For example, if we have an array named val then valand &val[0] can be used interchangeably. If we assign this value to non-constant pointer of the same type, then We can access the elements of the array using this pointer, i 1 Array to R28 1 INTRODUCTION TO PROGRAMMING —LBTECIT ESEM BF Example 1: Accessing Array Elements u: ng Pointer with Array Subscript Valo} Valli} val[2} = 10 Ss ptrlo] ptt) ptrl2} 1 C Program to access array elements using pointer Hinclude void main() { {Declare an array int valf3] = { 5, 10, 15 }; Declare pointer variable int* ptr; 1 Assign address of valf0] to ptr. I We can use ptr=&vall0};(both are same) ptr= val; printf(" Elements of the array are: "); Printf("%d, %d, %a!, ptr[0], ptr), pte(2)); } Output Elements of the array are: 5 10 15 oo Not only that, as the array elements are stored continuously, we can pointer arithmetic operations such as increment, decrement, addition, and subtraction of integers on pointer to move between array elements, vio von vial 10 [ 100. 200 Suppose I have a pointer ptr pointing at base address of one dimensional array. To access nth element of array using pointer we use *(ptr + n) (where ptr points to Oth element of array, n is the nth element to access and nth element starts from 0). JIC Program to access array elements using pointers include main() { int myNumbers(4] = {1, 2,3, 4); prints("%2d", *(pur + i)); Prepared By B.Narasimha Rao (BNR), Associate Professor, UNIT-AIN INTRODUCTION TO PROGRAMMING = [-BTECH I-SEM — BR23 } ) Output 1234 Two Dimensional array to pointer:how to access a two dimensional array through pointer Let us suppose a two-dimensional array int matrix{3](3]; For the above array, matrix => Points to base address of two-dimensional array. Since array decays to pointer. *(matrix) => Points to first row of two-dimensional array. _ie.. *(matrix) “(matrix+0) => Points to first row of two-dimensional array. ie.. *(matrix+i) “(matrix +1) => Points to second row of two-dimensional array. ie... *(matrix+i) **matrix => Points to matrix{0)[0) ie.. *(*(matrix+i)+j) *(*(matrix+0)) => Points to matrix{0}[0] ie, *(*(matrix+i)+j) *(*(matrix +0) +0)=> Points to matrix{0}{0] ie. *(*(matrix+i)+j) “(tmatrix +1) => Points to matrix{0]{1] *(*(matrix +0)+1)=> Points to matrix{0][1] “(*(matrix +2) +2) => Points to matrix{2][2] Note: If you are not familiar with *(matrix + 2) syntax then please give yourself time and leam pointer arithmetic in C. T have tried to summarize two dimensional array access using pointer in below image. [2 | scrcnatrtx + 0) + o> 2 | scrcmaertx + 0) + a9 3 | scecnaertx + 0) + 29 sEmateix + ©) =| a | s [6 | *cmateix + 2) Cnateix + a) + 09 matrix +a) + 49 7 [® | > | scmatetx + 2) natrixt3](3] *erqnatetx + 2 + 2) cnatrix + 2) + 02 sernatetx + 22D, sCrenatetx + 2) + 2 Tw Program to access a two dimensional array using pointer /*C program to access two dimensional array using pointer.*/ #include #tdefine ROWS 3 Prepared By B. isimha Rao (BNR), Associate Professor, CSE Dept, Odalareu Page 23 F 2 UNIT-IIT INTRODUCTION TO PROGRAMMING —-FBTEC 1 1-SEM BR2 define COLS 3 /* Function declaration to input and print two dimensional array */ void inputMatrix(int matrix{][COLS], int rows, int cols): void printMatrix(int matrix[][COLS}, int rows, Int cols); maing) {int matrixfROWS][COLS},i, js printi"Enter elements in %dx%d matrix.\n", ROWS, COLS); inputMatrix(matrix, ROWS, COLS); —_/* Print elements in matrix */ print{t" Elements of %dx%d matrix.\n", ROWS, COLS); printMatrix(matrix, ROWS, COLS); } /*Function to take input in two dimensional array (matrix) from user. matrix 2D array to store input and rows -> Total rows in 2D matrix. cols -> Total columns in 2D matrix.*/ void inputMatrix(int matrix{][COLS), int rows, int cols) ;j header file to facilitate dynamic memory allocation in C programming. They are: 1. malloc() 2. calloc() 3. free() 4. realloc() L.malloc() function: The “malloc” or “memory allocation” method in C is used to dynamically allocate a single large block of memory with the specified size, It returns a pointer of type void which can be cast into a pointer of any form. It doesn’t Initialize memory at execution time so that it has initialized each block with the default garbage value initially. Syntax of malloc() in C ae Prepared By B.Narasimha Rao (BNR), Associate Profe rept. BV Odalaret Page UNIT-HI INTRODUCTION TO PROGRAMMING — I-B Pointer variable = (cast-type*) malloe(bytc-size) For Example: pir = (int*) malloc(100 * sizeoftint); Since the size of int is 4 bytes, this statement will allocate 400 bytes of memory. And. the pointer pir holds the address of the first byte in the allocated memory. Malloc() Int* ptr =(int*) malloc (S* sizeof (int )); ‘ r= Sai ens & = Example of malloc() in C include #include main() { 1! This pointer will hold the base address of the block created int* ptr; int n, i; // Get the number of elements for the array printf{"Enter number of elements:"); seanf("%d" &n); printf("Entered number of elements: %din',n); W Danial allocate memory using malloc() int*)malloc(n * sizeof{int)); “7 Check ithe memory has been succesfily allocated by malloc or not if (ptr = NULL) { printf("Memory not allocated.\n"); exit(0); else {1 Memory has been successfully allocated printf("Memory successfully allocated using malloc.\n"); 1 Get the elements of the array for (i= 0; i Hinclude int main() 1) This pointer will hold the ase address of the block created int* ptr; int n, i; 1/ Get the number of elements for the array. n=5; printf("Enter number of elements: %d\n", n); / Dynamically allocate memory using calloc() pir = (int*)ealloe(n, sizeofint ‘Associate Professor, CS jpared By B.Narasimha Rao (BNR), = . 23 UNIT- INTRODUCTION TO PROGRAMMING —LBTECH ESEM BM 1. Check if the memory has been successfilly allocated by ealloc or not if (ptr = NULL) { printf{"Memory not allocated.\n"); exit(0): } alse { // Memory has been successfully allocated print{(”Memory successfully allocated using calloc.\n"); 11 Get the elements of the array for (i= 0; i include int main() {This pointer will hold the bi int ptr UNIT INTRODUCTION TO PROGRAMMING —-BEECH SPM int n, 5 ‘/ Get the number of elements for the array n=5; print{("Enter number of elements: Yad\n", n); / Dynamically allocate memory using calloc() pir=(int*)ealloe(n, sizeoftint)); 1 Check if the memory has been successfully allocated by malloc or not if (ptr = NULL) { printf{"Memory not allocated.\n"); exit(0); } else {i Memory has been successfully allocated printf("Memory successfully allocated using calloc.\n"); Get the elements of the array for (i= 0;i vai { // This pointer will hold the base address of the block created int *ptr, *ptrl, n, i; n= 5;// Get the number of elements for the array Printf("Enter number of elements: %d\n", n); ptr = (int*)malloc(n * sizeof(int)); // Dynamically allocamemory using malloc() ptr] = (int*)calloc(n, sizeof(int));// Dynamically allocate memory using calloc() /i Check if the memory has been successfully allocated by malloc or not if (ptr = NULL || ptrl = NULL) { printf("Memory not allocated.\n"); exit(0); } else { // Memory has been successfully allocated print{("Memory successfully allocated using malloc.\n"); free(ptr);// Free the memory printf("Malloc Memory successfully freed.\n"); // Memory has been successfully allocated print{("\wMemory successfillly allocated using calloc.\n"); free(ptrl); // Free the memory printf("Calloc Memory successfully freed.\n"); :M — BR23 UNIT-I INTRODUCTION TO PROGRAMMING —L-BTECIL Fs 1 1 OutputzEnter number of elements: 5 Memory successfully allocated using malloc. Malloc Memory successfully freed. Memory successfully allocated using calloc. Calloc Memory successfully freed. Command Line Arguments: Define main() with two arguments: the first argument is the number of command-line arguments and the second is a list of command-line arguments. Syntax: int main(int arge, char *argy[]) (/*...*/} or int main(int arge, char **argv) { /*... */ } Here, arge (ARGument Count) is an integer variable that stores the number of command-line arguments passed by the user including the name of the program. So if we pass a value toa program, the value of arge would be 2 (one for argument and one for program name) The value of argc should be non-negative. argy (ARGument Vector) is an array of character pointers listing all the arguments. If arge is greater than zero, the array elements from argv(0] to argv[argc-1] will contain pointers to strings. argv(0) is the name of the program , After that till argv[arge-1] every element is command - line arguments.For better understanding run this code on your Linux machine. include int main(int argc, char* argv{])// defining main with arguments { printf("You have entered %d arguments:\n", argc); for (int i= 0; i main(int arge, char* argv{]) { printf("Program name is: %s", argv{0)); if (arge = 1) print{("\nNo Extra Command Line Argument Passed Other Than Program Name"): if(arge>=2) { _printf("\nNumber Of Arguments Passed: %d", arge printf("\n----Following Are The Command Line Arguments Passed for (int i= 0; i< arge; i+) printf("\nargy[%d]: %s", i, argv(i)); ) } Output in different scenarios: 1. Without argument: When the above code is compiled and executed without passi argument, it produces the following output. Terminal Input: S /a.out Output:Program Name Is: /a.out ‘No Extra Command Line Argument Passed Other Than Program Name 2. Three arguments: When the above code is compiled and cxecuted with three arguments, it produces the following output. ‘Terminal Input: $ J/a.out First Second Third Output:Program Name Is: /a.out Number Of Arguments Passed: 4 --Following Are The Command Line Arguments Passed- argy(0): /a.out argy(1]: First argy(2]: Second argy(3): Third 3. Single Argument: When the above code is compiled and executed with a single argument separated by space but inside double quotes, it produces the following output Terminal Input: $ /a.out "First Second Third” Output: Program Name Is: /a.out Number Of Arguments Passed: 2. --Following Are The Command Line Arguments Passed- argy{0}: /a.out argy[1}: First Second Third Prepared By B.Narasimha Rao (BNR), Associate Professor, CSE Dept. ,BVCEC, Odalareu Pa ing any UNIT-ITL INTRODUCTION TO PROGRAMMING —-EBTECIE SEM BR24 argy[arge] is a NULL pointer, argy[0] holds the name of the program, argy[1] points to the first command line argument and are argument, Note: You pass all the command line arguments separated by a space, but if the argument itself has a space. then you can pass such arguments by putting, ther inside double quotes ingle quotes ". ge-I] points to the bt //C program to illustrate command line arguments, #include main(int arge, char* argv{]) { printf("Program name is: %s", argv{0)); if (arge = 1) _ print{("No Extra Command Line Argument Passed Other Than Program Name"): if(arge>=2) { _printf("\nNumber Of Arguments Passed: Yd". arge printf("\n----Following Are The Command Line Arguments Passed for (int i= 0; i< arge; i+) printf(“\nargy[%d]: %s", i, argv(i)); ) } Output in different scenarios: 1. Without argument: When the above code is compiled and executed without passi argument, it produces the following output. Terminal Input: $ J/a.out Output:Program Name Is: /a.out ‘No Extra Command Line Argument Passed Other Than Program Name 2. Three arguments: When the above code is compiled and executed with three arguments, it produces the following output. Terminal Input: $ ,/a.out First Second Third Output:Program Name Is: /a.out Number Of Arguments Passed: 4 --Following Are The Command Line Arguments Passed- argv[0): /a.out argy[l): First argv (2): Second argy(3]: Third 3. Single Argument: When the above code is compiled and executed with a sit argument separated by space but inside double quotes, it produces the following output Terminal Input: $ ./a.out "First Second Third" Output: Program Name Is: /a.out Number Of Arguments Passed: 2 --Following Are The Command Line Arguments Passed- argy{0]: /a.out argy[1]: First Second Third ha Rao (BNR), Associate Professor, CSE Dept. ,BVCEC, Odalareu Pa; ing any Prepared By B.Narasi

You might also like