Search code examples
c++pointersstrstr

Why strstr() - char pointer = number?


I have this program:

#include <iostream>
#include <conio.h>
#include <string.h>

using namespace std;

int main()
{
  char char1[30] = "ExtraCharacter", char2[30] = "Character", *p;

  p = strstr(char1, char2);
  cout << "p: " << p << endl;
  cout << "char1: " << char1 << endl;
  cout << "(p-char1): " << (p-char1) << endl;

  return 0;
}

When I run it, I get:

p: Character
char1: ExtraCharacter
(p-char1): 5

as expected.

But this is not the problem, I'm not sure why "Character" - "ExtraCharacter" is an integer (5)? Perhaps not an integer, but a number/digit anyways. Actually I don't understand why is "Character" stored in p, and not the memory address.

If I understood well from a book, strstr() returns a memory address, shouldn't it be more like a strange value, like a hex (0x0045fe00) or something like that? I mean, it's cout << p not cout << *p to display the actual value of that memory address.

Can someone explain me how it works?

P.S.: I apologize if the title is not that coherent.


Solution

  • But this is not the problem, I'm not sure why "Character" - "ExtraCharacter" is an integer (5)?

    You subtract one pointer from another and result - number, distance from char char1 points to to char p points to. This is how pointer arithmetic works.

    Note: this subtraction is only valid when both pointers point to the same array (or behind the last element), which is the case in your code, but you need to be careful. For example if strstr() does not find susbtring then it would return nullptr and your subtraction will have UB. So at least check p before subtracting (and passing nullptr to std::cout would have UB as well)

    If I understood well from a book, strstr() returns a memory address, shouldn't it be more like a strange value, like a hex (0x0045fe00) or something like that? I mean, it's cout << p not cout << *p to display the actual value of that memory address.

    Yes p is a pointer aka memory adress. std::ostream has special rule how to print pointers to char - as strings, because strings in C stored that way. If you want to see it as a pointer just cast it:

    std::cout << static_cast<void *>( p );
    

    then you will see it as an address.