4

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?

2 Answers 2

6

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Any idea why I might be getting this warning: "sumIt_dec.c:93:11: warning: assignment makes integer from pointer without a cast [enabled by default] "?
@Lokesh This could happen if you are assigning a result of a pointer expression to a variable of numeric type.
Aha! Problem solved. Thanks! I was thinking the problem is in my manipulation of pointer to the next element.
4

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.