Pointer to the next element of the array

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

Suppose I have a line

s = "Hello World"

      

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

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

      

How do I get a pointer to a given one, I just know p?

+3


source to share


2 answers


If you know that the pointer to an array element does not point to the last element in the array, the expression p+1

will point to the next element in the array. This rule works regardless of the type of the array element, if the base type of the pointer is the same as the type of the array element: the compiler makes all the necessary adjustments when performing the addition.

So in your example, strchr

print *(p+1)

will print a space.



Demo version

+5


source


As dasblinkenlight already said, 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.

+4


source







All Articles