Pointer Arithmetic in C Language

Dear Sciaku Learner you are not logged in or not enrolled in this course.

Please Click on login or enroll now button.

If you have any query feel free to chat us!

Happy Coding! Happy Learning!

In C language, pointer arithmetic allows you to perform mathematical operations on pointers. This can be useful for traversing arrays, manipulating memory, and other tasks.

The basic pointer arithmetic operations are:

  • Incrementing a pointer: ptr++ or ++ptr increments the pointer by the size of the type it points to.
  • Decrementing a pointer: ptr-- or --ptr decrements the pointer by the size of the type it points to.
  • Adding or subtracting an integer to/from a pointer: ptr + n or ptr - n increments or decrements the pointer by n times the size of the type it points to.

Here is an example of pointer arithmetic for traversing an array:

Copy code

#include <stdio.h> int main() {    int a[5] = {1, 2, 3, 4, 5};    int* p = a;  // p points to the first element of the array    for (int i = 0; i < 5; i++) {        printf("%d ", *p);        p++;  // Increment the pointer to point to the next element    }    printf("\n");    return 0; }

In this example, the pointer p is set to point to the first element of the array a. The for loop iterates 5 times, and in each iteration, it prints the value at the current position of the pointer using the dereference operator (*), then increments the pointer to point to the next element of the array, until it reaches the end of the array.

It's important to mention that, the pointer arithmetic operations only work with pointers that point to elements of an array or a block of memory allocated dynamically, it cannot be used with pointers to single variables or function pointers.

It's also worth noting that, when you increment or decrement a pointer to an array, it doesn't change the actual array, it just changes the position of the pointer, also it's not allowed to increment a pointer over the array's boundary, that could lead to undefined behavior.

8. Pointers

Comments: 0

Frequently Asked Questions (FAQs)

How do I register on Sciaku.com?
How can I enroll in a course on Sciaku.com?
Are there free courses available on Sciaku.com?
How do I purchase a paid course on Sciaku.com?
What payment methods are accepted on Sciaku.com?
How will I access the course content after purchasing a course?
How long do I have access to a purchased course on Sciaku.com?
How do I contact the admin for assistance or support?
Can I get a refund for a course I've purchased?
How does the admin grant access to a course after payment?