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)
In this call
the function
strchr
returns a pointer that points to the symbol'e'.
In the expression
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)
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 arraystr
to pointer) points to the first element of the array.