Reputation: 3112
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?
Upvotes: 4
Views: 17862
Reputation: 5239
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.
Upvotes: 4
Reputation: 726539
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.
Upvotes: 6