Okay so I've been wrestling with this for two days for a total of well over 20 hours. I've read through the tutorial on this site and five other sites, watched a YouTube vid about it and read my book. A few times over. I normally wouldn't ask, but I have this week to learn about pointers and classes and more about classes and inheritance. That's about 150 pages in my book. I am getting a little stressed over this.
I've been sitting with this up for 20 minutes and I still don't know how to concretize what I am asking for into a question. Any example involving a function with pointers (including one as an argument for that function) and char type variables with a nice step by step walkthrough on what's what will do... I hope.
I want myString to print out "Hello!" but it prints out "Good-bye.", so obviously my function isn't doing what I want it to do. Why? And any suggestions on how to make it so?
Your converter function is not actually changing the pointer you are passing.
1 2 3 4 5
void converter(constchar *aString)
{
constchar *charPointer = "Hello!"; //make a local variable
charPointer = aString; //make it point to whatever aString is pointing at
}
Anyway, you can't actually change myString since it is a const char*. That means it is a pointer to some constant (unchangeable) data, so if you try to modify it you will get an error.
Have you looked at the tutorial for pointers on this site? Try that if you haven't already.
Yeah, I have looked through them. I always look through the tutorials here before I read my book, just so that I'll have a better idea. Up until functions with pointers, I felt like I had a fairly good grip on what the tutorial wanted to tell me.
Okay so for the sake of argument (pun intended), let's assume that we rewrite the code so that every pointer with a const char type is instead a regular char type. So in my function, I make charPointer point at "Good-bye." which is what aString is pointing at. Okay, that makes sense. So how do I change myString, assuming that it now is not a const char?
Unfortunately, you picked the most annoying thing to try to modify...in that case, you would have to allocate some memory dynamically and assign that to the pointer. Then you would copy the data into the pointer. Also, you would have to pass a double pointer (a char**) since passing just the char* would mean you aren't changing the original variable.
Would it be possible to use an std::string? It would make it a *lot* easier.
If you want to use a pointer to change just data in general (for example an int), that is easier to understand and explain.
You could return charPointer and assign the output of the function to myString, but more importantly, if you want to learn about pointers, I suggest you find a copy of Let Us C by Yashavant P. Kanetkar and read pages 178-189. I was having trouble with pointers for about a year until I read those 11 pages. I know everyone has their own favorites, but I'm pretty sure that will clear up any trouble you may have.
@firedraco: Sounds like a bit much for something so simple, although I might try to do for practice... however, I don't know why I'm having this much trouble. Maybe it's because I haven't been presented with a concrete example of why/when to/how to actually use pointers together with functions...
Here's something stupid thrown together:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
void addition(int *x, int *y, int *z)
{
int **m = &y;
int **n = &z;
*x += 10;
**m += 10;
**n -= 5;
}
int main()
{
int a = 1, b = 2, c = 5;
addition(&a, &b, &c);
std::cout << a << std::endl;
std::cout << b << std::endl;
std::cout << c << std::endl;
}
And looking at this code, although I wouldn't know immediately what it does, I wouldn't have to look at it for more than seconds. It makes sense to me. But whenever we're dealing with chars and pointers and arrays together with functions, I just get lost right away. I'm trying to work with chars because there is an exercise in my book where I am asked to take a text string and print it out backwards. The conditions are to use two pointers, and one of the arguments in the function should be a pointer to the string.
rojSarton: I'll see if my library has that book, though I doubt it. Last time I checked, a few weeks ago, they had NO books on either C or C++, and maybe a couple on C#.
Ah. Yeah, that doesn't particularly surprise me since in C, char* is generally used for holding a string.
Anyway, to do that, you would need to take advantage of how pointers work. For example, this piece of code will print out each character in a string until it reaches a '\0' character:
1 2 3 4 5 6
void print_c_str(constchar* str) {
while(*str != '\0') { //check to make sure the character we are at is not '\0'
std::cout<<*str; //print out that character
++str; //increment the pointer (char* is like an array, so ++str will go to the next char)
} //keep going till we hit a '\0'
}
Try modifying that so that it runs until it hits a second pointer passed (using this prototype):
void printC(constchar *aString)
{
int j = strlen(aString) - 1;
for (int i = 0; i <= j; i++) //
std::cout << *(aString + j - i);
}
Is above an acceptable solution? I know I didn't follow the suggested prototype, but this solution kind of just popped up in my head. Anything I can learn from this? Like, can my solution be potentially harmful, is it inferior (relative to my level)? Anything that can help me understand more would be appreciated.
OFF-TOPIC: This programming course is the third and last course I'm having (because there aren't anymore). The first two were two and three weeks, respectively, I did them both in three weeks and got the highest grade. This one is five weeks but I have to do it in three if I want to apply for university next semester. This course deals with pointers, classes (including friendship and inheritance), container classes, libraries, exceptions, templates, dynamic data structures and some other things. Which sounds like an insane amount of things to digest in such a short time and spit out an A+ project (the last week is always for the project and final exam).
So yeah, helping me through pointers so I can continue with classes is a real, real life saver. So I wanted to let you know that I'm very grateful for all your help! =)
It would probably work, but firedraco's solution is better IMO. strlen() already loops through the string looking for a null character ('\0') to determine the length, so using it to find the length of the string won't help at all. I don't see why you are doing all that strange pointer arithmetic on line 5, either. It would be much better and more straightforward to simply write: aString[i].
The point of the exercise is to use pointers. The task of the exercise is to print out the characters of the string in reverse order. So "Hello!" should come out as "!olleH", which is what the arithmetic in line 5 is doing. It starts out with the last element that is not the null terminating character, and works it way backwards until it reaches the first element.
I'm using strlen() to make int j more flexible, as opposed to assigning a mathematical constant to j. That way I don't need to modify any code depending on what's in that char array.
Not sure how I would implement firedraco's solution, but I'm looking at it now (had to take a break because the girlfriend wanted to talk for a while).
Ah, apologies, I noticed your were actually printing the reversed string as your problem stated. I still think the pointer arithmetic, while valid, looks odd. I don't see any reason not to use the subscript operator[].
No problems =) Do you have any suggestions on how to make it look better? (I think it looks a little silly too, if not using pointers I'd have probably gone with aString[j - i] which looks better I suppose. But since the exercise is strictly about pointers... it is after all an exercise and I know enough to not rush pointers as I'm sure I will regret it later, much like I regretted rushing through strings and arrays.
Besides possibly giving j a better name, nothing really jumps out as something I would change. Though I have to say, I don't see the subscript operator as being any less "pointer-related" than using the explicit pointer arithmetic. It's just syntactic sugar; saying the arithmetic is about pointers while the other isn't is like claiming that (*ptrToClass).member is more about pointers than the simpler ptrToClass->member.
Well, the thing is that a char* is generally regarded as more of an array (an array of chars is basically a string), not really a pointer. Anyway, what I was getting at with my suggestion was something like this: