简体   繁体   中英

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?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM