Pointers & Arrays

Apr 18, 2016 at 10:56pm
My assignment starts with giving us the following strlen() function which will return the length of a null-terminated character-array:

1
2
3
4
5
6
7
8
unsigned int strlen(const char s[])
{
    unsigned int n;

    for (n = 0; s[n]; n++); // same as s[n] != '\0'

    return n;
}


Then it gives us the same function but using pointers:

1
2
3
4
5
6
7
8
unsigned int strlen(const char * s)
{
    unsigned int n;

    for (n = 0; *(s+n); n++);

    return n;
}


I have to write a main() for it that would test the correctness of both. I have no clue where to start...my program looks like this right now but I'm lost on where to go or what to focus on doing.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include <vector>
#include <algorithm>

unsigned int strlen(const char s[])
{
    unsigned int n;

    for (n = 0; s[n]; n++); // same as s[n] != '\0'

    return n;
}

unsigned int strlen(const char * s)
{
    unsigned int n;

    for (n = 0; *(s+n); n++);

    return n;
}

int main()
Last edited on Apr 18, 2016 at 10:56pm
Apr 19, 2016 at 12:12am
You need a main() function that calls each of your strlen functions in turn, with a known string, and checks that the result each function returns is the value you expect for that known string.
Apr 19, 2016 at 12:25am
So far my main is this:
1
2
3
4
5
6
7
int main()
{
    char one[20] = "abcd";
    char two[20] = "xyz";

     cout << "The first string: " << strlen(one) << " The second string: " << strlen(two) << endl;
}


but I keep getting an error message when I run the program:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
$ g++ -c PointerArrays.cpp
PointerArrays.cpp: In function ‘int main()’:
PointerArrays.cpp:31:6: error: ‘cout’ was not declared in this scope
      cout << "The first string: " << strlen(one) << " The second string: " << strlen(two) << endl;
     
PointerArrays.cpp:31:6: note: suggested alternative:
In file included from PointerArrays.cpp:1:0:
/usr/include/c++/4.8.2/iostream:61:18: note:   ‘std::cout’
   extern ostream cout;  /// Linked to standard output
            
PointerArrays.cpp:31:94: error: ‘endl’ was not declared in this scope
      cout << "The first string: " << strlen(one) << " The second string: " << strlen(two) << endl;
                                                       
PointerArrays.cpp:31:94: note: suggested alternative:
In file included from /usr/include/c++/4.8.2/iostream:39:0,
                 from PointerArrays.cpp:1:
/usr/include/c++/4.8.2/ostream:564:5: note:   ‘std::endl’
     endl(basic_ostream<_CharT, _Traits>& __os)
 
Apr 19, 2016 at 12:30am
Nevermind, realized I didn't add using namespace std;
Thank you for the help.
Apr 19, 2016 at 9:52am
You're welcome - glad it all worked.
Topic archived. No new replies allowed.