why strlen is subtrcting value of i in place of addition.

Write your question here.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include<iostream> 
#include<cstring>
using namespace std;

class IndiaBix
{
    char txtMsg[50]; 
    public:
    IndiaBix(char *str = NULL)
    {
    if(str != NULL)
       strcpy(txtMsg, str);
    }
    int BixFunction(char ch);
};
int IndiaBix::BixFunction(char ch)
{
    static int i = 0;
    if(txtMsg[i++] == ch){
    	cout<<"i="<<i<<"\tstrlen((txtMsg))="<<strlen(txtMsg + i)<<endl;
        return strlen((txtMsg + i)) - i;
    }
    else
        return BixFunction(ch);
}
int main()
{
    IndiaBix objBix("Welcome to IndiaBix.com!");
    cout<< objBix.BixFunction('t');
    return 0;
}
txtMsg decays to a pointer (char*) to the first element in the txtMsg array.
1
2
"Welcome to IndiaBix.com!"
 ^


When you add i to the pointer you get a pointer that points i positions forward. It's the same pointer you get by doing &txtMsg[i].
1
2
3
"Welcome to IndiaBix.com!"
          ^
          txtMsg + 9


When this pointer is passed to strlen it will start counting from the position where the pointer is pointing.
1
2
3
"Welcome to IndiaBix.com!"
          ^_____________^
           distance = 15
Last edited on
Topic archived. No new replies allowed.