Download Poniters , Strings and Arrays in C programming and more Lecture notes C programming in PDF only on Docsity!
UNIT IV
Pointers A pointer is defined as a derived data type that can store the address of other C variables or a memory location. We can access and manipulate the data stored in that memory location using pointers. the pointers store the memory addresses, their size is independent of the type of data they are pointing to. Syntax The syntax of pointers is similar to the variable declaration in C, but we use the (
- ) dereferencing operator in the pointer declaration. datatype * ptr ; where
- ptr is the name of the pointer.
- datatype is the type of data it is pointing to. How to Use Pointers? The use of pointers can be divided into three steps:
- Pointer Declaration
- Pointer Initialization
- Dereferencing
- 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; The pointer declared here will point to some random memory address as it is not initialized. Such pointers are called wild pointers.
- Pointer Initialization Pointer initialization is the process where we assign some initial value to the pointer variable. We generally use the ( & ) addressof operator to get the memory address of a variable and then store it in the pointer variable. 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.
- Dereferencing 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. #include void func1() { int var = 10; // declare pointer variable int* ptr; // note that data type of ptr and var must be same ptr = &var; // assign the address of a variable to a pointer printf("Value at ptr = %p \n", ptr); printf("Value at var = %d \n", var); printf("Value at *ptr = %d \n", *ptr); } int main() { func1(); return 0;
C Pointers and Arrays An array name acts like a pointer constant. The value of this pointer constant is the address of the first element. For example, if we have an array named val then val and &val[0] can be used interchangeably. Example 1: Accessing Array Elements using Pointer with Array Subscript #include void fun() { // Declare an array int val[3] = { 5, 10, 15 }; // Declare pointer variable int* ptr; // Assign address of val[0] to ptr. // We can use ptr=&val[0];(both are same) ptr = val; printf("Elements of the array are: "); printf("%d, %d, %d", ptr[0], ptr[1], ptr[2]); return; } int main() { fun(); return 0;
Uses of Pointers The C pointer is a very powerful tool that is widely used in C programming to perform various useful operations. It is used to achieve the following functionalities in C:
- Pass Arguments by Reference
- Accessing Array Elements
- Return Multiple Values from Function
- Dynamic Memory Allocation
- Implementing Data Structures
- In System-Level Programming where memory addresses are useful.
- In locating the exact value at some memory location.
- To avoid compiler confusion for the same variable name.
- To use 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, trees, etc.
- 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 in C.
- Pointers are comparatively slower than variables in C. Arrays Array in C is one of the most used data structures in C programming. It is a simple and fast way of storing multiple values under a single name. An array in C is a fixed-size collection of similar data items stored in contiguous memory locations. It can be used to store the collection of primitive data types such as int, char, float, etc., and also derived and user- defined data types such as pointers, structures, etc.
C Array Initialization Initialization in C is the process to assign some initial value to the variable. here are multiple ways in which we can initialize an array in C.
- Array Initialization with Declaration data_type array_name [size] = {value1, value2, ... valueN};
- Array Initialization with Declaration without Size data_type array_name[] = {1,2,3,4,5}
- Array Initialization after Declaration (Using Loops) for (int i = 0; i < N; i++) { array_name [i] = value i ; } #include int main() { // array initialization using initialier list int arr[5] = { 10, 20, 30, 40, 50 }; // array initialization using initializer list without // specifying size int arr1[] = { 1, 2, 3, 4, 5 }; // array initialization using for loop float arr2[5]; for (int i = 0; i < 5; i++) { arr2[i] = (float)i * 2.1; } return 0;
Access Array Elements
We can access any element of an array in C using the array subscript operator [ ] and the index value i of the element. One thing to note is that the indexing in the array always starts with 0, i.e., the first element is at index 0 and the last element is at N ā 1 where N is the number of elements in the array. Example of Accessing Array Elements using Array Subscript Operator #include
int main() { // array declaration and initialization int arr[5] = { 15, 25, 35, 45, 55 }; // accessing element at index 2 i.e 3rd element printf("Element at arr[2]: %d\n", arr[2]); // accessing element at index 4 i.e last element printf("Element at arr[4]: %d\n", arr[4]); // accessing element at index 0 i.e first element printf("Element at arr[0]: %d", arr[0]); return 0;
Example of 1D Array in C #include int main() { // 1d array declaration int arr[5]; // 1d array initialization using for loop for (int i = 0; i < 5; i++) { arr[i] = i * i - 2 * i + 1; } printf("Elements of Array: "); // printing 1d array by traversing using for loop for (int i = 0; i < 5; i++) { printf("%d ", arr[i]); } return 0; } Array of Characters (Strings) In C, we store the words, i.e., a sequence of characters in the form of an array of characters terminated by a NULL character. These are called strings in C language. #include int main() { // creating array of character char arr[6] = { 'G', 'e', 'e', 'k', 's', '\0' }; // printing string int i = 0; while (arr[i]) { printf("%c", arr[i++]); }
return 0;
2. Multidimensional Array in C Multi-dimensional Arrays in C are those arrays that have more than one dimension. A Two-Dimensional array or 2D array in C is an array that has exactly two dimensions. They can be visualized in the form of rows and columns organized in a two-dimensional plane. Syntax of 2D Array in C array_name[size1] [size2]; Here,
- size1: Size of the first dimension.
- size2: Size of the second dimension. Example of 2D Array in C #include int main() { // declaring and initializing 2d array int arr[2][3] = { 10, 20, 30, 40, 50, 60 }; printf("2D Array:\n"); // printing 2d array for (int i = 0; i < 2; i++) { for (int j = 0; j < 3; j++) { printf("%d ",arr[i][j]); } printf("\n"); } return 0;
Return an Array from a Function in C In C, we can only return a single value from a function. To return multiple values or elements, we have to use pointers. We can return an array from a function using a pointer to the first element of that array. #include // function int* func() { static int arr[5] = { 1, 2, 3, 4, 5 }; return arr; } int main() { int* ptr = func(); printf("Array Elements: "); for (int i = 0; i < 5; i++) { printf("%d ", *ptr++); } return 0; } Properties of Arrays in C
- Fixed Size The array in C is a fixed-size collection of elements.
- Homogeneous Collection We can only store one type of element in an array.
- Indexing in Array The array index always starts with 0 in C language.
- Contiguous Storage All the elements in the array are stored continuously one after another in the memory.
- Random Access The array in C provides random access to its element i.e we can get to a random element at any index of the array by using its index number.
Examples of Array in C Example 1: C Program to perform array input and output. In this program, we will use scanf() and print() function to take input and print output for the array. #include int main() { // declaring an integer array int arr[5]; // taking input to array elements one by one for (int i = 0; i < 5; i++) { scanf("%d", &arr[i]); } // printing array elements printf("Array Elements: "); for (int i = 0; i < 5; i++) { printf("%d ", arr[i]); } return 0; } Example 2: C Program to print the average of the given list of numbers In this program, we will store the numbers in an array and traverse it to calculate the average of the number stored. #include // function to calculate average of the function float getAverage(float* arr, int size) { int sum = 0; // calculating cumulative sum of all the array elements for (int i = 0; i < size; i++) { sum += arr[i]; } // returning average return sum / size;
Advantages of Array in C The following are the main advantages of an array:
- Random and fast access of elements using the array index.
- Use of fewer lines of code as it creates a single array of multiple elements.
- Traversal through the array becomes easy using a single loop.
- Sorting becomes easy as it can be accomplished by writing fewer lines of code. Disadvantages of Array in C
- Allows a fixed number of elements to be entered which is decided at the time of declaration. Unlike a linked list, an array in C is not dynamic.
- Insertion and deletion of elements can be costly since the elements are needed to be rearranged after insertion and deletion. Strings In C language, a string is a collection of characters stored in a character array and terminated with a null character '\0'. Example: char name[10] = "Vision"; Here the string "Sumit" is stored as: V i s i o n \ 0 Declaring and Initializing Strings char s1[20]; char s2[20] = "Hello"; char s3[] = "Welcome"; char s4[6] = {'H','e','l','l','o','\0'}; Reading & Writing Strings Input scanf("%s", str); fgets(str, 20, stdin); Output printf("%s", str); puts(str); Arithmetic Operations on Characters char c = 'A'; printf("%d", c); // 65 (ASCII) char x = 'A' + 2; // becomes 'C'
String-Handling Functions (#include ) Function Meaning strlen(s) Find length of string strcpy(a, b) Copy b to a strcat(a, b) Join b to the end of a strcmp(a, b) Compare a and b strupr(s) Convert lowercase to uppercase strlwr(s) Convert uppercase to lowercase strrev(s) Reverse string Examples of Each Function
- strlen() ā Length of String #include #include int main() { char str[30] = "Hello World"; printf("Length = %d", strlen(str)); return 0; }
- strcpy() ā Copy String #include #include int main() { char source[20] = "Computer"; char target[20]; strcpy(target, source); printf("Copied String = %s", target); return 0; }
- strcat() ā Concatenate Strings #include #include int main() { char s1[30] = "Hello "; char s2[20] = "Students"; strcat(s1, s2); printf("Concatenated String = %s", s1); return 0; }
- strcmp() ā Compare Strings #include #include int main() { char a[10] = "Apple";