RoR
RoR

Reputation: 16482

C++ escape character difference in osx and windows?

I'm playing around with C++ in xcode and well i'm having an issue with

char array[] = "Apple"; 

Technically a null escape '\0' is automatically added. I'm just writing a basic function to add the number of letters in the c-string but i go into a forever loop because it can't find the '\0'. Why is that? I'm using g++.

int CharLength(char* word)
{
    char* temp = word;
    int count = 0 ;

    while ( temp != '\0' )
    {
        temp++;
        count++;
    }

    return count;
}

Upvotes: 2

Views: 216

Answers (3)

Thomas Edleson
Thomas Edleson

Reputation: 2196

Use strlen from the <cstring> or <string.h> headers.

Upvotes: 2

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798716

You forgot to dereference.

while ( *temp != '\0' )

Upvotes: 5

Ernest Friedman-Hill
Ernest Friedman-Hill

Reputation: 81694

"temp" will not be 0 until you've looked at all of memory and wrapped around! On the other hand *temp will be zero when you get to the end of the string. The loop condition should be

while ( *temp != '\0' )

Upvotes: 3

Related Questions