Incrementing pointers for *char in a while loop

20,040

Solution 1

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.

Solution 2

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.

Solution 3

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!

Share:
20,040
Bbvarghe
Author by

Bbvarghe

Updated on April 24, 2020

Comments

  • Bbvarghe
    Bbvarghe about 4 years

    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?