Search code examples
c++pointerspointer-arithmetic

In c++ using pointer arithmetic


How do you display the last character in a character array when you don't know how big the array is? Would array *('\0' - 1) work?


Solution

  • If a character array contains a C-style string, ie it contains a null terminator, then you can apply the standard C function strlen(), like this:

    char s[] = "Hello";
    //...
    size_t n = strlen( s );
    
    if ( n != 0 ) std::cout << s[n-1] << '\n';
    

    Otherwise, you can write a template function like this:

    template <size_t N>
    char last_char( const char ( &s )[N] )
    {
        return s[N-1];
    }
    

    and call it like this:

    char s[] = { 'H', 'e', 'l', 'l', 'o' };
    
    std::cout << last_char( s ) << '\n';