I'm rewriting a program for an assignment in my c++ class where we need to change a c-string array which gets a line of text and then counts a user-inputted letter (so if you enter something like "and ant addy author awesome" and count the letter "a" you'll get an answer as 5).
The goal is to change the array to a pointer. I have the original program written, but my book is pretty useless as for given valuable instruction. And we don't like the material till the next class (so you teach yourself and then they teach you[pretty dumb, huh?])
Let's use this chunk of code as an example of what I want to do
I think the errors is on line 14. An array is a pointer so you should only pass text. Just like you can do this:
1 2
char array[256];
char *ptr = array;
Same with how when you pass by array you are really passing by the memory address.
Then another error you have is on line 8.
Basically you are doing this
1 2 3
char array[25];
cin.getline( array[0] , 256 );
The pointer by default points to the first element in the array. So you are trying to input 256 characters into a single character. Also shouldn't you be using size instead of 256?
So I'm making a pointer, setting it equal to text, sending it to getText, but I'm still getting an issue with cin.getline. You said something about the pointer pointing to the first element in the array, and basically that's changing the element 256 times, how do I get past that? I guess my issue at this point in time is I don't understand at all what I'm really trying to do, I know what I need to do, but I don't understand how to go about it. Am I making the pointer into an array? Am I making the array into a pointer? How do I save a c-string as a pointer?
void getText(char *pText) // <- pText is a char* (a pointer)
{
cout << "Enter some text: ";
cin.ignore(0);
cin.getline(*pText); // <- therefore *pText is a char (a single character)
// passing a single character to getline is wrong -- you need to pass it the pointer
// so it knows where to write the string data. Do this instead:
cin.getline( pText );
// but you should REALLY give it a buffer size so you don't go outside the bounds
// of this array
}
Also
1 2 3 4 5 6 7 8 9 10 11
int main ()
{
char text[256];
char *pText = text; // this is correct. pText is a char* (pointer)
getText(&pText); // since pText is already a pointer, doing &pText
// gives you a pointer to a pointer (ie: char**)
// This is wrong.. since getText takes a char*, not a char**
// You want to do this:
getText( pText ); // since getText takes a char*... and pText is a char*
// no conversion necessary... just pass it
EDIT:
although... you don't really need pText in main... and you can just do this: