nbarbop24 nbarbop24 - 1 year ago 133
C++ Question

Finding the length of a C style char * string in c++

The point of this program is to reverse a string and print it out. It is a school assignment and I'm just starting it. I need to reverse the string that was given to me (the whole main function was given for the assignment) and I need to do it by using 2 pointers for the beginning of the cstring and the end of the cstring. In the code, I know that the beginning of the cstring that is passed would be just "temp" but I don't know how I could find the ending letter of the cstring and assign a pointer to it.

The main function was given to me:

#include <iostream>
#include "reverse.hpp"

using namespace std;
void reverse(char*);

int main()
// these are the test cases
char str1[] = "time";
char str2[] = "straw";
char str3[] = "deliver";
char str4[] = "star";
char str5[] = "knits";

cout << "The strings before reversing: " << endl;
cout << str1 << " " << str2 << " " << str3 << " " << str4 << " " << str5 << " " << endl;


cout << "The strings after reversing: " << endl;
cout << str1 << " " << str2 << " " << str3 << " " << str4 << " " << str5 << " " << endl;

return 0;


Here is the reverse function:

#include <string.h>

void reverse(char*temp)
// *temp would equal "t" in the first cstring
// (sizeof *temp - 1) would equal last character ???


#endif // REVERSE_HPP

This is different than others that were posted because I'm trying to get the length with a pointer

Answer Source

just for completeness

void reverse(char*temp)
    int l = strlen(temp);

For extra credit, re-implement the whole assignment (main as well) using c++ strings, which is what you should use in c++. Also put the strings in a vector rather than n separate variables.

Sigh - I see somebody else already did the first one for you.You could still make the reverse function work on the std::string rather than c_str(). Note that c++ has a oneliner for you that will reverse the string - find that for extra extra credit

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download