returning a char as a pointer
Just after a little help here, I've shrunk the code down to keep it simpile, and I'm hoping there is an obvious reason why it wont return the character that I enter, any thoughts?? The same way seems to work for int and doubles but not for char.
Code:
void position (char, char *);
int main (void);
{
char orientation;
char orien;
position(orientation, *orien);
printf("Orientation is: %c", orien);
fflush(stdin);
getc(stdin);
return 0;
}
void position (char orientation, char *orien)
{
scanf("Selection is: %c", &orientation);
*orien = orientation;
}
Re: returning a char as a pointer
Try this:
Code:
void position (char, char *);
int main (void);
{
char orientation;
char *orien;
position(orientation, orien);
printf("Orientation is: %c", *orien);
fflush(stdin);
getc(stdin);
return 0;
}
void position (char orientation, char *orien)
{
scanf("Selection is: %c", &orientation);
*orien = orientation;
}
Re: returning a char as a pointer
Quote:
Originally Posted by
Vanilla_Rice
Code:
void position (char, char *);
int main (void);
{
char orientation;
char orien;
position(orientation, *orien);
//...
}
This doesn't compile. Fix the compiler errors first.
Quote:
Originally Posted by
Tronfi
Try this:
Your code has undefined behaviour. You are dereferencing an uninitialised pointer. It's a good custom to initialise any pointer you define with 0 or a valid address.
Then when you dereference a pointer, check that it's not 0.
Code:
void position (char orientation, char *orien)
{
if (!orien) {
throw std::invalid_argument("NULL pointer");
}
scanf("Selection is: %c", &orientation);
*orien = orientation;
}
Re: returning a char as a pointer
Code:
int main (void);
{
char orientation;
char orien;
position(orientation, &orien);
printf("Orientation is: %c", orien);
fflush(stdin);
getc(stdin);
return 0;
}
void position (char orientation, char *orien)
{
scanf("Selection is: %c", &orientation);
*orien = orientation;
}
Re: returning a char as a pointer
thanks for the reply's, I have it working now.
Re: returning a char as a pointer
That code looks quite weird to me. None of the two parameter are really needed:
1) The first parameter is used to store a letter from keyboard input. There“s no need to pass it, it should be local.
2) Only the second parameter is modified and the function does not return anything. It should return the letter typed in by the user
Code:
char position()
{
char orientation;
scanf( "Selection is %c", &orientation );
return orientation;
}
int main()
{
char orientation = position();
}
Using C++ streams might even be a better solution.