Pointer Subtraction in C - C Programming Tutorial 94

preview_player
Показать описание
Notes for You:: Pointer Subtraction in C - C Programming Tutorial 94
- If two pointer variables are of same type and they are pointing to the elements of the same array, then they can be subtracted from one another.

ptr2 – ptr1 returns
- total memory locations the two pointer variables are offset or away from one another.

(ptr2 – ptr1) – 1 returns
- total memory locations available in between two pointer variables.

(ptr2 – ptr1) + 1 returns
- total elements available in an array; if ptr1 is pointing to the first memory location of the array and ptr2 is pointing to the last memory location of the array .

Note: ptr2 – ptr1 // is implicitly expanded to (ptr2 - ptr1) / size of pointer variable’s type.

Note: Most commonly; two pointer variables are subtracted from one another to get
- total memory locations; the two pointer variables are offset or away from one another.
- total memory locations; available in between two pointer variables.
- total elements; available in an array;

Note: addition, multiplication, and division of pointer variables are not supported.

Example Code:
#include <stdio.h>
int main()
{
int numbers[5] = {1,2,3,4,5};
int *ptr1 = &numbers[0];
int *ptr2 = &numbers[4];

printf("%d\n", ptr2 - ptr1); // 4
printf("%d\n",(ptr2 - ptr1) - 1); // 3
printf("%d\n",(ptr2 - ptr1) + 1); // 5
return 0;
}

Note:
- replace < with less-than symbol.
- replace > with greater-than symbol.

=========================================

Follow the link for next video:

Follow the link for previous video:

=========================================

C Programming Tutorials Playlist:

=========================================
Watch My Other Useful Tutorials:-

Computer Programming Fundamentals Playlist:-

C Practical LAB Exercises Playlist:-

C++ Tutorials Playlist:

=========================================

► Subscribe to our YouTube channel:

► Visit our Website:

=========================================
Hash Tags:-
#ChidresTechTutorials #CProgramming #CProgrammingTutorial
Рекомендации по теме