This code will output the index of a charcter in a string :
#include <stdio.h>
#include <string.h>
int main(void){
char str[100]="birds are dying";
char *p;
p = strchr(str,'e');
int i=p-str;
printf("%d" , i);
return 0;
}
the only line of code that i can't understand is :
int i=p-str;
str is a string and p also , i searched about the result of printing a string as an integer and found that it is an undefined behaviour , so what does it actually return ?
p - str is : e dying - birds are dying
, when somehow we change it to an integer why does it return a positive value
Thanks
From the C Standard (6.3.2.1 Lvalues, arrays, and function designators)
3 Except when it is the operand of the sizeof operator or the unary & operator, or is a string literal used to initialize an array, an expression that has type ‘‘array of type’’ is converted to an expression with type ‘‘pointer to type’’ that points to the initial element of the array object and is not an lvalue. If the array object has register storage class, the behavior is undefined
In this call
p = strchr(str,'e');
the function strchr
returns a pointer that points to the symbol 'e'.
In the expression
p-str
The object str having the array type char[100]
is implicitly convereted to pointer to its first element. So the expression represents a difference of two pointers.
And according to the C Standard (6.5.6 Additive operators)
9 When two pointers are subtracted, both shall point to elements of the same array object, or one past the last element of the array object; the result is the difference of the subscripts of the two array elements....
Thus the difference is the number of elements between two pointers that yields the index of the found symbol because the expression str
(after implicit conversion of the array str
to pointer) points to the first element of the array.