* (e-mail address removed) (BlindHorse) schriebt:
I need someone to tell me why I am getting the err msg
error C2440: '=' : cannot convert from 'char *' to 'char'
Uhum. There are more serious problems than that in the code.
//====================
#include <iostream>
using namespace std;
char *Input();
Here is one big problem: who is responsible for deallocating the
memory returned by function 'Input'?
That problem leads to directly to a memory leak in your program,
discussed below.
Instead of 'char*', I suggest you make the return type 'std::string'.
Here there's a problem in usage. It's only by the good grace of
old C compatibility that this 'Output' function can be used with
a literal string as an argument, because the argument type says
that 'Output' is free to change the string. Instead use e.g.
'char const []' as argument type.
//====================
void main()
This is not allowed by the standard.
Function 'main' must have return type 'int'.
Nothing else.
{
char *iptr = new char [100];
*iptr = Input();
The basic misunderstanding seems to be that you're thinking in
terms of assigning an array, complete, whereas what the code
attempts to do is to assign a pointer.
'*iptr' does not refer to the 100 character array you've just
allocated, as you might think.
Instead, since 'iptr' is a pointer to 'char', '*iptr' is a single
'char'.
Namely, the first character in that array.
Figure.
Draw one box representing the 'iptr' variable.
Draw one hundred small boxes representing the array.
Draw an arrow from within 'iptr' to the first array element.
The compiler only uses what the arrow points directly at.
It doesn't know or care that there's 99 elements further on.
So you're trying to assign the result of function 'Input', which is
a pointer to char, to a single char.
The compiler won't have any of that unless you force it to.
Output(iptr);
delete [] iptr;
}
You can make this _compile_ by removing the dereferencing:
char *iptr = new char [100];
iptr = Input();
Output(iptr);
delete [] iptr;
But then the assignment replaces the address of the one hundred bytes
you allocated.
Then you don't have that address available any longer for deallocation.
And the 'delete' will just deallocate the array allocated by 'Input'.
So here you have the memory leak mentioned earlier on.
//====================
char *Input(void)
Style: 'void' for argument list is a C'ism best a-voided in C++.
{
char *name = new char [100];
cout << "Enter name: ";
cin >> *name;
return name;
}
//====================
void Output(char *input)
{
cout << *input;
cout << endl;
}
Many of the problems will go away simply by using 'std::string'
instead of 'char*'.
The function signatures would then be:
std::string Input();
void Output( std::string const& );
And you then need to #include <string> at the top of the program.
Hth.