Docsity
Docsity

Prepare for your exams
Prepare for your exams

Study with the several resources on Docsity


Earn points to download
Earn points to download

Earn points by helping other students or get them with a premium plan


Guidelines and tips
Guidelines and tips

Pointers in C Programming, Lecture notes of C programming

Explains Pointers in C and Its examples

Typology: Lecture notes

2020/2021

Uploaded on 12/12/2021

sanskar-unkule
sanskar-unkule 🇮🇳

5

(1)

4 documents

1 / 51

Toggle sidebar

Related documents


Partial preview of the text

Download Pointers in C Programming and more Lecture notes C programming in PDF only on Docsity! WE ys SITES RISE WITH EDUCATION Peo nog Chapter 6 Pointers FE - C Programming Prof. Namrata Jiten Patel Assistant Professor Dept. of Computer Engineering, SIES Graduate School of Technology Objectives :To provide exposure to problem-solving by developing an algorithm, flowchart and implement the logic using C programming language Outcomes: Learner will be able to... 1. Understand the concept of pointers WE ys er SITES RISE WITH EDUCATION mrata Jiten Patel Understanding memory allocation ¢ All computers have primary memory, also known as RAM or random- access memory. * For example, a computer may have 16, 32, 64, 128, 256, or 512 MB of RAM installed. * RAM holds the programs that the computer is currently running along with the data they are currently manipulating * All the variables used in a program (and indeed, the program itself) reside in the memory when the program is executed. ¢ When a program in C is written and compiled, the compiler will allocate the memory necessary to run the program. WE ys ary Computer memory * Int x; e X=1000; Addr Mem : 0 1 i 2 2 3 char ‘a’ in 3 4 7 7| memory 4 5 5 One Ss location . fx] int number i 1000 in oul 27576 / Piaae 27si7 / ne 27577 say r number 27578 NA ys SITES RISE WITH EDUCATION Tero Te ony Namrata Jiten Patel Address of Operator(&) * Readers might have noticed that when we call certain functions in C the & sign is used. * For example, * scanf(“%d”, &n); Takes the input from the terminal and stores it in integer format in the variable named n. WE yk er SITES RISE WITH EDUCATION mrata Jiten Patel * The syntax for declaring a pointer variable is datatype * pointer variable: * where, datatype is the type of data that the pointer is allowed to hold the address of (that is, the type of data that the pointer is allowed to point to) and pointer_variable is the pointer variable name that is used to refer to the address of a variable of type datatype. WE ys ary ¢ An example of a pointer declaration would be ¢ char *ptr; * The above declaration should be evaluated as: ptr is a pointer to char type data. char is not the data type of ptr. * ptr is an identifier of type pointer and char is a data specifier that is used to indicate what type of data is at the memory address that ptr is holding. ¢ Pointers are variables that hold memory addresses. At the memory address, held in a pointer, is a value; this value has a data type of one of the C data types or a user-defined data type (e.g., structure). WE ys ary Example: int *a; * The above declaration indicates that a is a pointer type variable that points to int type data. * That is, the int indicates that the pointer variable is intended to store the address of an integer variable. Such a pointer is said to ‘point to’ an integer. float *t; ¢ The above declaration represents the fact that t is a pointer type variable that points to float type data. WE ys ary Why should pointers have data-type * Point:1 * When objects of a given data type are stored consecutively in the memory (that is, an array), each object is placed at a certain offset from the previous object, if any, depending on its size. WE ys ary Why should pointers have data-type * Point:2 ¢ Acompiler that generates a code for a pointer, which accesses these objects using pointer arithmetic, requires information on generating offset. WE ys ary Why should pointers have data-type * Point:3 Sizes of various data types are basically decided by the machine architecture and/or the implementation. WE ys Stet Indirection Operator and Dereferencing ¢ The primary use of a pointer is to access and, if appropriate, change the value of the variable that the pointer is pointing to. ¢ The other pointer operator available in C is ‘*’, called the ‘value at address’ operator. ¢ It returns the value stored at a particular address. * The value at address operator is also called indirection operator or dereference operator. WE yk er SITES RISE WITH EDUCATION #include <stdio.h> int main() { int num = 5; int *iPtr = &num; printf(“\n The value of num is %d”, num); num = 10; printf(“\n The value of num after num = 10 is\ %d”, num); *iPtr = 15; printf(“\n The value of num after *iPtr = 15 is\ %d”, num); return 0; } Output: The value of num is 5 The value of num after num = 10 is 10 The value of num after *iPtr = 15 is 15 WG Namrata Jiten Patel RISE WITH EDUCATION ¢ The placement of the indirection operator before a pointer is said to dereference the pointer. ¢ The value of a dereferenced pointer is not an address, but rather the value at that address—that is, the value of the variable that the pointer points to. * For example, in the preceding program, iPtr’s value is the address of num. However, the value of iPtr dereferenced is the value of num. Thus, the following two statements have the same effect, both changing the value of num. * num = 25; ¢ *iPtr = 25; * Similarly, a dereferenced pointer can be used in arithmetic expressions in the same fashion as the variable to which it points. Thus, the following two statements have the same effect. * num *= 2; ¢ *iPtr *= 2; WE Sys Cee eo SITES mrata Jiten Patel RISE WITH EDUCATION WE Re ary NULL POINTER * A null pointer is a special pointer that points nowhere. ¢ That is, no other valid pointer to any other variable or array cell or anything else will ever be equal to a null pointer. * The most straightforward way to get a null pointer in the program is by using the predefined constant NULL, which is defined by several standard header files, including <stdio.h>, <stdlib.h>, and <string.h>. * To initialize a pointer to a null pointer, code such as the following can be used. ¢ #include <stdio.h> * int *ip = NULL; mrata Jiten Patel *#include <stdio.h> *int main() *{ *int *p; ¢p = NULL; *printf(“\n The value of p is %u”, p); *return 0; *} * Output: *The value of p is 0 WE Points to note ¢ NULL is a constant that is defined in the standard library and is the equivalent of zero for a pointer. ¢ NULL is a value that is guaranteed not to point to any location in memory. *#include <stdio.h> eint main(void) “{ ¢char *p=NULL; * printf (“%s”,p); ereturn 0; pointer to an array of characters. Since NULL is not an array of characters, the statement “printf (“%s”,p);” shows an undefined behaviour resulting in unpredictable or compiler defined output. WE RISE WITH EDUCATION Assignment * Pointers with the assignment operators can be used if the following conditions are met. ¢ The left-hand operand is a pointer and the right-hand operand is a null pointer constant. * One operand is a pointer to an object of incompatible type and the other is a pointer to void. * Both the operands are pointers to compatible types. WE ys er SITES RISE WITH EDUCATION mrata Jiten Patel #include <stdio.h> int main() { int i=5; int *ip; void *vp; ip = &i; vp = ip; * printf(“\n *vp= %d”,*((int *)vp)); * printf(“\n *ip= %d”,*ip); WE ys FF SIES li ip = vp; return 0; } Output: *yp=5 *ip=5 RISE WITH EDUCATION Namrata Jiten Patel Addition or Subtraction with In teger 3 equivalent to the expression (&(arr[3])). * arr[3] is equivalent to *(arr + 3). ¢ #include <stdio.h> * int main(void) of * int al] = {10, 12, 6, 7, 2}: ¢ int i; ¢ int sum = 0; ¢ int *p; “pra * for(i=0; i<5; i++) of * sum += *p; °pt; +} * printf(“%d\n”, sum); * return 0; ot WE ys er SITES RISE WITH EDUCATION ¢#include <stdio.h> eint main(void) “f{ eint a[] = {10, 20, 30, 40, 50}; eint i, *p; *for(p=a; p<=at4; p++) *printf(“%sd\n", *p); ereturn 0; °} ¢ Output: -10 * 20 30 - 40 °50 «Note: Here each time p is compared with the base address of the array. WE ys ary Dynamic Memory Allocation in C ¢ Manual allocation and freeing of memory according to your programming needs. ¢ Dynamic memory is managed and served with pointers that point to the newly allocated memory space in an [area whjch we call the heap. * To sum up, the automatic memory management uses the stack, and the C Dynamic Memory Allocation uses the heap. WA ys aIFS Tone amrata Jiten Patel Library used for Dynamic Memory Allocation <stdlib.h> Purpose Allocates the memory of requested size and returns the pointer to the first byte of allocated space. Allocates the space for elements of an array. Initializes the elements to zero and returns a pointer to the memory. Itis used to modify the size of previously allocated memory space. Frees or empties the previously allocated memory space. WE Namrata Jiten Patel Example #include <stdlib.h> int main(){ int *ptr; ptr = malloc(15 * sizeof(*ptr)); /* a block of 15 integers */ if (ptr != NULL) { ¥(ptr + 5) = 480; /* assign 480 to sixth integer */ printf("Value of the 6th integer is %d",*(ptr + 5)); } Output: Value of the 6th integer is 480 NA ys SITES RISE WITH EDUCATION Namrata Jiten Patel Notice 1.sizeof(*ptr) was used instead of sizeof(int) in order to make the code more robust when *ptr declaration is typecasted to a different data type later. 2.The allocation may fail if the memory is not sufficient. In this case, it returns a NULL pointer. So, you should include code to check for a NULL pointer. 3.Keep in mind that the allocated memory is contiguous and it can be treated as an array. We can use pointer arithmetic to access the array elements rather than using brackets [ ]. 4.We advise to use + to refer to array elements because using incrementation ++ or += changes the address stored by the pointer. 5.Malloc() function can also be used with the character ype as well as complex,.data types such as ures. MG Mi SS The free() Function ¢ The memory for variables is automatically deallocated at compile time. In dynamic memory allocation, you have to deallocate memory explicitly. ¢ If not done, you may encounter out of memory error. ¢ The free() function is called to release/deallocate memory in C. ¢ By freeing memory in your program, you make more available for use later. WE ays SITES Bs RISE WITH EDUCATION Namrata Jiten Patel Syntax and example Syntax of calloc() Function: ptr = (cast_type *) calloc (n, size); W%~ yt SIES RISE Namrata Jiten Patel WITH EDUCATION 45 Example of calloc() #include <stdio.h> int main() { int i, * ptr, sum = 4; ptr = calloc(10, sizeof(int)); if (ptr == NULL) { printf("Error! memory not allocated."); exit(®); 3 printf("Building and calculating the sequence sum of the first 18 terms \ n "); for (i = @; i < 10; ++i) { * (ptr + i) = i; sum += * (ptr + i); } printf("Sum = %d", sum); free(ptr); return @; Building and calculating the sequence sum of the first 10 terms Sum = 45 Namrata Jiten Patel 46 SITES RISE WITH EDUCATION Difference between calloc and malloc calloc() function is generally more suitable and Malloc is less preferred than calloc efficient than that of the malloc() function Both allocates memory Both allocates memory calloc() in C is used to allocate multiple blocks of Malloc() function is used to allocate a single block of memory space memory space Each block allocated by the calloc() function is ofthe - same size Malloc() function can also be used with the The calloc() function is used in complex data character data type as well as complex data types structures which require larger memory space. such as structures. The memory block allocated by a calloc() in C is malloc() in C, it always contains a garbage value always initialized to zero WE Re SITES RISE WITH EDUCATION romance Namrata Jiten Patel #include <stdio.h> int main () { char *ptr; ptr = (char *) malloc(10); strcpy(ptr, "Programming") ; printf(" %s, Address = %u\n", ptr, ptr); ptr = (char *) realloc(ptr, 20); //ptr is reallocated with new size strcat(ptr, "In 'C'"); printf(" %s, Address = %u\n", ptr, ptr); free(ptr); return 0; Namrata Jiten Patel Thank You!! namratap@sies.edu.in Namrata Jiten Patel 51
Docsity logo



Copyright © 2024 Ladybird Srl - Via Leonardo da Vinci 16, 10126, Torino, Italy - VAT 10816460017 - All rights reserved