### Array subscripting to Pointers

I am suppose to write this program in two ways one with array subscripting which I have done below. The other way with pointers and pointer arithmetic. Not sure how to go about the second way or how to convert the one below from array subcripting to pointers.

#include <iostream>
#include <iomanip>
using namespace std;

int stringLength1(char* s)
{
int count;
for ( count = 0; s[count] != 0; count++ );
return count;
}

int stringLength2(char* s)
{
int count = 0;
while ( *s++ != 0 ) count++;
return count;
}

char* stringCopy1(char* s1, char* s2)
{
int count;
for ( count = 0; s2[count] != 0; s1[count] = s2[count], count++ );
s1[count] = 0;
return s1;
}

char* stringCopy2(char *s1, char *s2)
{
while ( *s2 != 0 ) *s1++ = *s2++;
*s1 = 0;
return s1;
}

char* stringCat1(char* s1, char* s2)
{
stringCopy1(&s1[stringLength1(s1)], s2);
return s1;
}

char* stringCat2(char* s1, char* s2)
{
stringCopy2(&s1[stringLength2(s1)], s2);
return s1;
}

int main() {

// Implement the following function prototypes
int stringLength1(char *s );
int stringLength2(char *s );
char *stringCopy1( char *s1, char *s2 );
char *stringCopy2( char *s1, char *s2 );
char *stringCat1( char *s1, char *s2 );
char *stringCat2( char *s1, char *s2 );

char s1[ 100 ];
char* s2 = "education";
char* s3 = "school";

// Test stringLength functions
cout << "stringLength1(" << s2 << "): " << stringLength1( s2 ) << endl;
cout << "stringLength2(" << s3 << "): " << stringLength2( s3 ) << endl;

// Test stringCopy functions
cout << "stringCopy1(s1, " << s2 << "): " << stringCopy1( s1, s2 ) << endl;
cout << "stringCopy2(s1, " << s3 << "): " << stringCopy2( s1, s3 ) << endl;

// Test stringCat functions
cout << "stringCat1(s1, " << s2 << "): " << stringCat1( s1, s2 ) << endl;
cout << "stringCat2(s1, " << s3 << "): " << stringCat2( s1, s3 ) << endl;

return 0; // indicates successful termination
} // end main
`p[i]` is the same as `*(p + i)` if `p` is a pointer or an array and `i` is an integer.
Last edited on
Topic archived. No new replies allowed.