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.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments