Arrays and Pointers

Hey guys, I am very new to C++ and I have a question about arrays and pointers when it comes to determining string length. This is what it's asking:

Write two versions of each of the following functions. The first version (1) should use array subscripting. The second version (2) should use pointers and pointer arithmetic. Place the functions in the same file as main and following the main function:

int stringLength(const char* s);

Determines the length of string s. The number of characters preceding the terminating null character is returned.



This is what I've gotten for the first part of the problem, but I don't understand what it means for the second part "should use pointers and pointer arithmetic."


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>
using namespace std;

int stringLength1(char *s)
{
    int index = 0;
    
    for (index = 0; index <100; index++)
    {
         if (s[index] == '\0')
         {        
              return index;
         }
    }
    
}

int main()
{
  char *s2 = "education";
  
  cout << stringLength1(s2) <<endl;

  system("pause");
  return 0;
}


Thanks,
wolfpack4417
Hi, this is the pointer arithmetics version

1
2
 
if (*(s + index) == '\0')


You can read more about it down below

http://www.cs.umd.edu/class/sum2003/cmsc311/Notes/BitOp/pointer.html
What does stringLength1 return if you fall through the loop?
There is no return statement at line 15.
Some handy reading:

http://zanasi.chem.unisa.it/download/C.pdf


Chapter 5 is about pointers & arrays.

HTH
Topic archived. No new replies allowed.