Can't understand the usage of strchr to get the position of a charcter in a string in C

340 views Asked by At

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;
  1. 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 ?

  2. p - str is : e dying - birds are dying , when somehow we change it to an integer why does it return a positive value

Thanks

2

There are 2 answers

0
Vlad from Moscow On BEST ANSWER

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.

5
cup On

It is not a string - it is a pointer. This is pointer arithmetic which is legal. It works in units of the pointees. Supposing you had

double x[10], *start, *end;
integer exclusive;

start = &x[2];
end = &x[4];
exclusive = end - start;
printf("%d\n", exclusive);

What do you think will be printed? You will get 2: not 2 * sizeof(double).