0

I'm currently completing some homework where we read an input, and load the input into a string, and stop reading when certain conditions are not met.

I've now been prompted to re-write my line 5 to involve pointer arithmetic, without square bracket notation.

int readLine(char*s, int MAX){
  char c;
  int i = 0;
  while((c = getchar()) != '\n' && i<MAX){
    s[i++] = c;
  }
  s[i]= '\0';
  return i;
}

would it be *s = i;?

Ismaeel Ali
  • 57
  • 1
  • 1
  • 6
  • If s is the address of the first element in the string, i.e. s = &s[0], and each character occupies a single byte, where might the fifth element of the string be located? Remember that arrays start at zero. You should be able to come up with an expression like s[i] = *(s + ....) – thurizas Oct 18 '22 at 14:15
  • the square notation is a quick/simpler way of addressing the value in a pointer. var[x] equals *(var+x) – mont_ Oct 18 '22 at 14:48
  • `char c; c = getchar()` is wrong. `getchar` returns an int, and if you want to reliably check for EOF, you must use an integer type. eg `int c; while( (c = getchar()) != EOF && c != '\n' && i < MAX )...`. (Note that this implies that failing to check for EOF is wrong, which is also true.) – William Pursell Oct 18 '22 at 15:00

1 Answers1

1

You are using pointer arithmetic. x[ y ] performs pointer arithmetic.

But you also said you want to avoid the square bracket syntax. Since x[ y ] is 100% equivalent to *( x + y ), that's easy.

Finally, the grader is possibly expecting you to go further and avoid adding i to s repeatedly. This can be done by modifying s itself.

ikegami
  • 367,544
  • 15
  • 269
  • 518