Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Incrementing pointers for *char in a while loop

Here is what I have:

char* input = new char [input_max]
char* inputPtr = iput;

I want to use the inputPtr to traverse the input array. However I am not sure what will correctly check whether or not I have reached the end of the string:

while (*inputPtr++)
{
    // Some code
}

or

while (*inputPtr != '\0')
{
    inputPtr++;
    // Some code
}

or a more elegant option?

like image 550
Bbvarghe Avatar asked Jun 14 '13 05:06

Bbvarghe


3 Answers

Assuming input string is null-terminated:

for(char *inputPtr = input; *inputPtr; ++inputPtr)
{
  // some code
}

Keep in mind that the example you posted may not give the results you want. In your while loop condition, you're always performing a post-increment. When you're inside the loop, you've already passed the first character. Take this example:

#include <iostream>
using namespace std;

int main()
{
  const char *str = "apple\0";
  const char *it = str;
  while(*it++)
  {
    cout << *it << '_';
  }
}

This outputs:

p_p_l_e__

Notice the missing first character and the extra _ underscore at the end. Check out this related question if you're confused about pre-increment and post-increment operators.

like image 167
greatwolf Avatar answered Sep 18 '22 10:09

greatwolf


I would do:

inputPtr = input; // init inputPtr always at the last moment.
while (*inputPtr != '\0') {      // Assume the string last with \0
       // some code
       inputPtr++; // After "some code" (instead of what you wrote).
}

Which is equivalent to the for-loop suggested by greatwolf. It's a personal choice.

Be careful, with both of your examples, you are testing the current position and then you increment. Therefore, you are using the next character!

like image 37
Maxime Chéramy Avatar answered Sep 21 '22 10:09

Maxime Chéramy


Assuming input isn't null terminated:

char* input = new char [input_max];
for (char* inputPtr = input; inputPtr < input + input_max; 
        inputPtr++) {
  inputPtr[0]++; 
}   

for the null terminated case:

for (char* inputPtr = input; inputPtr[0]; inputPtr++) {
      inputPtr[0]++; 
}   

but generally this is as good as you can get. Using std::vector, or std::string may enable cleaner and more elegant options though.

like image 30
perreal Avatar answered Sep 21 '22 10:09

perreal