Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pointer to next element of an array

I am struggling with a problem in C. The problem is how to get pointer to an element in array if I know the pointer to the previous element in the array?

Suppose I have a string

s = "Hello World"

and I have a pointer to 'o' in the string

char *p = strchr(s, 'o')

How do I get pointer to o given I just know p?

like image 599
Lokesh Avatar asked Oct 15 '25 19:10

Lokesh


2 Answers

If you know that the pointer to an array element is not pointing to the last element of the array, the expression p+1 will point to the next element of the array. This rule works regardless of the type of the array element, as long as the base type of the pointer is the same as the element type of the array: the compiler makes all the necessary adjustments when performing the addition.

Therefore, in your strchr example printing *(p+1) will print a space.

Demo.

like image 89
Sergey Kalinichenko Avatar answered Oct 18 '25 11:10

Sergey Kalinichenko


As dasblinkenlight already put it you can use "Pointer Arithmetic" for this.

If you have a pointer(p) and you add 'x' to it you get the 'xth' element from the location the pointer is at.

like image 40
Suvarna Pattayil Avatar answered Oct 18 '25 13:10

Suvarna Pattayil



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!