Re: [Dev-C++] Very simple Q 'm sure...
Open Source C & C++ IDE for Windows
Brought to you by:
claplace
|
From: Jason H. <jas...@bt...> - 2002-04-06 16:33:22
|
The * is the pointer operator. The program below is pretty bad, because it creates a pointer but
doesn't initialise it to point at anything, and when you get input to it you are writing to
unallocated memory, which could cause a memory access violation.
Books dedicate whole chapters to explaining what a pointer is and how to use them, so I won't here.
char *PName;
or
char* PName;
These two are the same statement really, declaring a pointer to a character or the start of an array
of characters. You should know that a null terminated array of characters in C/C++ represents a C
style string.
char PName;
This just declares a character. Essentialy allocating space for a single character (a byte) which is
why you get only one character from it.
A modified version of your program would be:
#include <iostream>
int main(int argc, char* argv[])
{
using namespace std;
char namebuf[32];
char *PName = namebuf;
cout << "Type passenger name\t";
cin >> PName;
cout << PName;
return 0;
}
Which won't cause any memory errors as long as the name doesn't go over 31 characters (remember 1
char for the null terminator).
Lookup pointers and arrays in your C++ reference of choice.
Jason.
----- Original Message -----
From: "Daniel Glenfield" <sp...@ho...>
To: <dev...@li...>
Sent: Saturday, April 06, 2002 4:37 PM
Subject: [Dev-C++] Very simple Q 'm sure...
Look at the declaration for PName. It is declared as char *PName. The line
cout<<PName; outputs the entire name.
HOWEVER if I declare the variable as char PName (with no *) only the first
letter is outputted.
Can anyone tell me what the * is doing?
Thanks,
Daniel
#include <iostream>
#pragma warning (disable : 4101)
int main(int argc, char* argv[])
{
using namespace std;
char *PName;
cout << "Type passenger name\t";
cin >> PName;
cout << PName;
return 0;
}
_________________________________________________________________
Get your FREE download of MSN Explorer at http://explorer.msn.com/intl.asp.
_______________________________________________
Dev-cpp-users mailing list
Dev...@li...
https://lists.sourceforge.net/lists/listinfo/dev-cpp-users
|