So, I am starting to familiarize with C, and at this point I'm trying to understand pointers. I got the following code from here, but I cannot comprehend, how does one subtract a character array from a pointer.
#include<stdio.h>
#include<string.h>
#include<conio.h>
main()
{
char s[30], t[20];
char *found;
/* Entering the main string */
puts("Enter the first string: ");
gets(s);
/* Entering the string whose position or index to be displayed */
puts("Enter the string to be searched: ");
gets(t);
/*Searching string t in string s */
found=strstr(s,t);
if(found)
printf("Second String is found in the First String at %d position.\n",found-s);
else
printf("-1");
getch();
}
Isn't the pointer only the address of a given variable/constant? When the subtraction happens the character array automatically assumes that since the operation happens with a pointer is subtracts its address? I am a bit confused here.
Thanks in advance.
Assuming you're wondering about the expression found-s
, then what's happening is that you subtract two pointers.
Arrays naturally decay to pointers to their first element. That means plain s
is equal to &s[0]
, which is what's happening here: found-s
is equal to found - (&s[0])
.
And the subtraction works because found
is pointing to an element inside the array s
, so the pointers are related (which is a requirement for pointer subtraction). The result is the difference (in elements) between the two pointers.