Explaining pointer notation

I need to remove all white spaces in a string from a code sample so that way it can print out as a character array. However, I must approach this by using pointer notation. I'd also like some helpful explanations or comments in the sample code concerning pointer notation. Here is the code:

#include<iostream>
using namespace std;

// Function Prototype
void trimSpcaes(char *str);
// Use only pointer Notation. Do not use array notation! do not use []

int main()
{
char str[] = "hi this is a test";
trimSpcaes(str);
}

Thank you.
Write your function using "array notation". Then, replace each occurrence of the built-in operator[] with its equivalent in "pointer notation".

For example, you might start with a program like this one:
1
2
3
4
5
void trim_spaces(char* s) 
{
  int i = 0, j = 0; 
  do if (s[i] != ' ') s[j++] = s[i]; while (s[i++]);
}

Then, you can use the fact that s[i] is exactly equivalent to *(s + i), and do the corresponding mechanical replacement to obtain something like this
1
2
3
4
5
void trim_spaces(char* s) 
{
  int i = 0, j = 0; 
  do if (*(s + i) != ' ') *(s + (j++)) = *(s + i); while (*(s + (i++)));
}

Then if you're observant you may notice that a simpler program is obtainable if we increment the pointer s instead of keeping the variable i to hold an offset:
1
2
3
4
5
void trim_spaces(char* s)
{
  char* t = s; 
  do if (*s != ' ') *t++ = *s; while (*s++);
}


P.S. "trim spaces" usually means removing white-space (only) from the ends.
Last edited on
Topic archived. No new replies allowed.