-1

I'm new to C++ and I'm now learning about pointers. I'm trying to understand this program:

#include <iostream>

int main() {
    char *text = "hello world";
    int i = 0;
    while (*text) {
        i++;
        text++;
    }
    printf("Char num of <%s> = %d", text, i);
}

It outputs:

Char num of <> = 11

But why not this:

Char num of <hello world> = 11

Barry
  • 286,269
  • 29
  • 621
  • 977

5 Answers5

3

As your increase text until it points to '\0', the string printed is empty.

Jarod42
  • 203,559
  • 14
  • 181
  • 302
2

You changed the value of text before printing it out:

#include <iostream>

int main() {
    // text starts pointing at the beginnin of "hello world"
    char *text = "hello world"; // this should be const char*
    int i = 0;
    while (*text) {
        i++;
         // text moves forward one character each time in the loop
        text++;
    }
    // now text is pointing to the end of the "hello world" text so nothing to print
    printf("Char num of <%s> = %d", text, i); 
}

The value of a char pointer (like text) is the location of the character that it is pointing to. If you increase text by one (using text++) then it points to the location of the next character.

Not sure why you #include <iostream> but use printf(). Typically in C++ code you would do this:

std::cout << "Char num of <" << text << "> = " << i << '\n';

A working example of what you are trying to do:

int main()
{
    const char* text = "hello world"; // should be const char*

    int length = 0;
    for(const char* p = text; *p; ++p)
    {
        ++length;
    }

    std::cout << "Char num of <" << text << "> = " << length << '\n';
}
Galik
  • 47,303
  • 4
  • 80
  • 117
  • Omg, Did I change the value of text variable by increase the pointer? I tried this and and I printf first variable, and worked! char *text = "hello world"; char *first = text; – Kaan Kölköy May 10 '15 at 16:02
  • @KaanKölköy Yes the value of a char pointer is the *location* of the character that it is pointing to, increase `text` and it points to the next character. – Galik May 10 '15 at 16:03
  • Well, thanks. So, Is there a way to print pointer variable after increase the pointer? I gave value of text to another variable and after that increased the pointer and finally printed that another variable. – Kaan Kölköy May 10 '15 at 16:11
  • No - typically in c++ you would never ever use char* = "whatever". You would never ever use a `while` for counting characters in a string. – Support Ukraine May 10 '15 at 16:15
  • It seems like you didn't understand what your own `while` loop was doing!! – Lightness Races in Orbit May 10 '15 at 16:29
  • @KaanKölköy yes you need to take a copy of the pointer. I will add a working example using a `for()` loop that makes a copy of `text` and increments that instead of incrementing `text`. – Galik May 10 '15 at 17:12
1

First of all - don't use char-string in c++! Use std::string.

Your while loop continues until it reach zero which is the string termination, so %s is just an empty string. The '<' and '>' is still printed even if the string is empty.

Your text pointer start as the following chars:

'h','e','l','l','o',' ','w','o','r','l','d','\0'

After the first loop, text points to:

'e','l','l','o',' ','w','o','r','l','d','\0'

After second loop, text points to:

'l','l','o',' ','w','o','r','l','d','\0'

And so on.

The while-loop continues until text points to '\0' which is just an empty string, i.e. "".

Consequently %s doesn't print anything.

In c++ do:

int main() {
   std::string text = "hello world";
   cout << "Char num of <" << text << "> = " << text.size() << std::endl;
}
Support Ukraine
  • 42,271
  • 4
  • 38
  • 63
  • My teacher used chars to teach us pointers. I don't know why. – Kaan Kölköy May 10 '15 at 16:15
  • 1
    In that case.... tell your teacher that c++ is not c - in any decent company you'll get sacked for using char arrays for string in c++ – Support Ukraine May 10 '15 at 16:18
  • 1
    And BTW - don't use pointers in c++. In most cases you don't have to. In most cases it is a design error - so reconsider the design instead. If you really, really need pointers you should consider unique_ptr and shared_ptr. – Support Ukraine May 10 '15 at 16:27
  • 1
    We didn't use char array for work with strings. We did it to learn pointers. If you can tell a better way, I can tell it to my teacher. Me too said it to teacher, but she wanting to teach us. – Kaan Kölköy May 10 '15 at 16:28
  • 1
    @Kaan It's an entirely antiquated approach to teaching C++ but, unfortunately, extremely commonplace. Just run with it then buy yourself [a modern C++ book](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) after the course completes. – Lightness Races in Orbit May 10 '15 at 16:33
  • @KaanKölköy - in case of text strings you should always use std::string. The standard library contains all the functions you'll need to operate on the string. Example is size/length but also all kind of search functions. For pointers in general - avoid them. For teaching about pointers a more appropriate case would be a vector holding pointers to instances of a class. Ok for teaching - seldom ok for a real program. – Support Ukraine May 10 '15 at 16:34
1

text is a pointer to a char. So when you increment the pointer you make it to point to the next element. The end of a string in C is delimited by the null character. So you are incrementing the pointer until it points to the null character. After that, when you call printf it doesn't print anything because it prints characters until reaches the null character but it is already at the null character.
This could be a quick fix:

#include <stdio.h>

int main() {
    char *text = "hello world";
    int i = 0;
    while (*text) {
        i++;
        text++;
    }
    printf("Char num of <%s> = %d", text-i, i);
}
tuket
  • 3,232
  • 1
  • 26
  • 41
0

After the loop pointer text points to the terminating zero of the string literal because it is increased in the loop.

Also function printf is declared in header <cstdio> And string literals in C++ have types of constant arrays (Though in C they have types of non-constant arrays. Nevertheless in the both languages you may not change string literals)

You can rewrite the program either like

#include <cstdio>

int main() {
    const char *text = "hello world";
    int i = 0;

    while ( text[i] ) ++i;

    std::printf("Char num of <%s> = %d\n", text, i);
}

Or like

#include <cstdio>

int main() {
    const char *text = "hello world";
    int i = 0;

    for ( const char *p = text; *p; ++p ) ++i;

    std::printf("Char num of <%s> = %d\n", text, i);
}

Also it is better instead of C function printf to use standard C++ stream operators.

For example

#include <iostream>

int main() {
    const char *text = "hello world";
    size_t i = 0;

    for ( const char *p = text; *p; ++p ) ++i;

    std::cout << "Char num of <" << text << "> = " << i << std::endl;
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335