0

I tried using following code sample given in Tour of C++ which uses nullptr to break loop over zero terminated string. However, my sample program doesn't seem to stop in the loop.

Excerpt from the book:

first version of code from book:

```

int count_x(char∗ p, char x)
// count the number of occurrences of x in p[]
// p is assumed to point to a zero-terminated array of char (or to nothing)
{
  if (p==nullptr) return 0;
  int count = 0;
  for (; p!=nullptr; ++p)
    if (∗p==x)
      ++count;
    return count;
}

```

second simplified version

```int count_x(char* p, char x)
// count the number of occurrences of x in p[]
// p is assumed to point to a zero-terminated array of char (or to 
// nothing)
{
    int count = 0;
    while (p) {
      if (*p==x)
        ++count;
      ++p;
    }
  return count;
}```

statement following code in the book: The while-statement executes until its condition becomes false. A test of a pointer (e.g., while (p)) is equivalent to comparing the pointer to the null pointer (e.g., while (p!=nullptr)).

My program using same structure:

char name[] = "ABCD";
char *p = name;
int count = 0;
int loopc = 0;
while (p)
{
    loopc++;
    if(*p == '\0')
        cout << "zero found\n";
    else 
        cout << *p << "\n";
    //emergency stop
    if (loopc == 12)
        break;
    p++;
}

expected: Should stop after printing name. actual: A B C D zero found zero found zero found zero found zero found zero found zero found zero found

  • 2
    `while (*p) {` . It's not the pointer that would become zero, but a character it points to. – Igor Tandetnik Dec 31 '18 at 20:18
  • @IgorTandetnik Hi. That's what my understanding is too from my experience with C language. I think it might be typo in book. Still, isn't nullptr limited to pointers only? How is author trying to use it to do check for zero char is what I am not getting. – dheeraj suthar Dec 31 '18 at 20:22
  • Don't rely on compiler to add a null termination to your string! Write char name[] = "ABCD\0"; – ravenspoint Dec 31 '18 at 20:23
  • 9
    @ravenspoint Nonsense. String literals are guaranteed to be NUL-terminated. – Igor Tandetnik Dec 31 '18 at 20:25
  • I don't see any mention of `nullptr` in the code that purportedly came from the book. I'm not sure what you are talking about. – Igor Tandetnik Dec 31 '18 at 20:26
  • @IgorTandetnik This is the second version of the code given by author (removed explicit nullptr). I have added his next line just after the code sample from book. I am also adding the original code excerpt from the book. – dheeraj suthar Dec 31 '18 at 20:30
  • Your program isn't using "same structure", or a remotely similar one. – n. m. could be an AI Dec 31 '18 at 20:32
  • 1
    Neither of the two code fragments shown mentions `nullptr`. I continue to fail to understand what you are talking about. What again do you feel is the problem, with what line of what piece of code? – Igor Tandetnik Dec 31 '18 at 20:35
  • @IgorTandetnik updated the code with author's code explicitly using nullptr – dheeraj suthar Dec 31 '18 at 20:36
  • The sample marked "first version of code from book" is just plain wrong. An increment operation `++p` will not magically turn a non-null pointer into a null pointer, no matter how many times performed. If it really came from a book, I would suggest disposing of said book in an environmentally responsible way, and acquiring [a better one.](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) – Igor Tandetnik Dec 31 '18 at 20:38
  • @IgorTandetnik Thanks! That's a relief. It baffled me for quite some time. Apparently this book is authored by Bjarne himself. Might be some editing mistake. – dheeraj suthar Dec 31 '18 at 20:42
  • Yes there's an error in the book. It may have been fixed in later printings. You cam view fragments of the book on Amazon and the error is fixed there. (**Both** quoted versions from the book are wrong and they are both fixed there). – n. m. could be an AI Dec 31 '18 at 20:49
  • @n.m. Just checked. Thanks! That's true. Feeling quite relieved. – dheeraj suthar Dec 31 '18 at 20:57
  • @IgorTandetnik Thanks for the list. Going through that. Funny thing though, this book is mentioned there too ;) – dheeraj suthar Dec 31 '18 at 20:58

2 Answers2

0

Thanks for all the useful comments.

It seems the author had given wrong example in the earlier edition (1st) which was later corrected in second edition released in 2018.

Corrected version from new edition:

int count_x(char∗ p, char x)
// count the number of occurrences of x in p[]
// p is assumed to point to a zero-terminated array of char (or to nothing)
{
  if (p==nullptr) return 0;
  int count = 0;
  for (; *p!=0; ++p)
    if (∗p==x)
      ++count;
    return count;
}
0

the first version should return 0 when you pass it nullptr. In the for loop however you are passing once. There is only one char* (consider using std::string btw) anyway... Here is my quick fix, try to understand it:

int count_x(char* c_ptr, char c) { 
  if (c_ptr == nullptr) return 0; 
  int count = 0; 
  /* Note that I check if *c_ptr is '\0' that's the **value** 
   * pointed to by c_ptr 
   */
  for (; *c_ptr != '\0'; ++c_ptr) // '\0' is a nul character 
    if (*c_ptr == c) ++count; 
  return count; 
} 

int foo(const std::string& word, char letter) noexcept { 
  int count = 0; 
  for (const auto& c: word) { // for all const char ref in word 
    if (c == letter) ++count;
  }
  return count;
}

int main() {
  int a = count_x("acbccc", 'c');
  int b = foo("acbccc", 'c');
  std::cout << a << '\n' << b;
}

Feel free to ask if you have any question. Cheers.

viraltaco_
  • 814
  • 5
  • 14