Ant's
Ant's

Reputation: 13811

Unexpected result in pointer arithmetic, in C

I'm new to C and I'm trying to solve one of the exercise problem of K&R book. The problem is to detect the whether a given string ends with the same content of other string.

For example, if string one is ratandcat and string two is cat. Then it is true that string two ends in string one. To solve this, I came up with half a solution and I got struck with pointers.

My idea is to find the position where string one ends and also the position the string two starts, so that I can proceed further. I have this code:

int strEnd(char *s,char *t){
    int ans,slength =0 ,tlength = 0;
    while(*s++)
        slength++;
    while(*t++)
        tlength++;
    s += slength - tlength;
    printf("%c\n",*t);
    printf("%c\n",*s);
    return ans;
}
void main() {
    char *message = "ratandcat";
    char *message2 = "at";
    int a = strEnd(message,message2);
}

But strangely this outputs :

%
(and a blank space)

But I want my s pointer to point to a. But it doesn't. Whats going wrong here?

Thanks in advance.

Upvotes: 0

Views: 111

Answers (2)

DigitalRoss
DigitalRoss

Reputation: 146271

One problem is that you have incremented the s pointer to the end of the string, and then you add more stuff to it. You could do that loop with something like:

while(s[slength])
  ++slength;

Another problem is that you are assuming that the s string is longer than the other. What if it's not? And fix the ; problem noted by Simon.

Upvotes: 2

Simon Richter
Simon Richter

Reputation: 29618

You have an extra semicolon at the end of

while(*t++);

This means that tlength is never incremented, as only the semicolon (empty statement) is executed in the loop.

Upvotes: 1

Related Questions