Yes this i an assingment for my C++ class. I just need a little help figuring out how to point to the end of a string. Basically we are suppose to create a char pointer that can be initialized to whatever. We can't use CString or String class or arrays. I can't figure out how to get the length of the string with out using strlen.
1 2 3 4 5 6 7 8 9 10 11 12 13
int main()
{
int i;
char *string;
string = "John Doe";
cout << "\nName is: " << string;
system("pause");
return 0;
}
this is what i have. I know that if i use *(string + 0) that will point to the first char in the string but how do i get it to point to the last char in the string. From the instruction John Doe could be changed to Sam and that would have to be printed in reverse. I don't want the whole program just some advice on the pointer part or maybe a link to something that would give a better clue then the tutorial here.
This is what i have got as almost finished product, except, it won't do the last for statement. cout << i << *(string + i) << endl; prints 7 and e for and using breakpoints on line 14 all the i's are 7, even the ones in the last for statement. Can't figured out why it won't do the last for statement.
okay last question how do i assign the value of *(string + i) to another string variable in my last for statement. This is what i have and the for statement works to decrement i but not for assigning.
1 2 3 4 5 6 7
for (i-=1; i >= 0; i--)
{
*(newstring + x) = *(string + i);
x++;
}
cout << "The name backwards is : " << string << endl;
Thanx Mathhead but my teacher specifically said we can't use arrays. Now i have a working version of the program it just seems a little cheap to me. In the code i have in this post i would like to know how to make my for statement work. Every time i run it i get an assignment error. I personally don't see how to make it work without using an array but I'm very new to this.
Yea, a c-string is an array (const char* == char[])
There is no way to get around that...
If you wanted to store this c-string in memory without a traditional array, you will need to define your own linked-list-style class...? I doubt that's what you want.
And yea the [] operator is just the offset operator, it offsets the pointer (i.e. pointer + offset) then dereferences it!
By the way... Normally you would avoid line 7 newstring = /* a very long string */ ;
by dynamically allocating an array, and storing it to that pointer. newstring = newchar[n]; //where n = length of string
(but I guess that uses arrays too...)
Thanks for your guy's help. I think the teacher was just wanting to emphasize the point that *(string + i); is the same thing as: string[i]. Again thanks.