CSE 459.22: Using pointers
I got a few questions about the use of pointers, hence this post.
I wrote a simple piece of code that uses pointers, char* etc.; try it out.
#include
int main() {
char* Months[12]; // creates Months[0], ..., Months[11]; each of these
// is a pointer; currently they are all uninitialized.
Months[0] = new char[21]; // this allocates 21 bytes and stores the
// address of the first byte in Months[0]
Months[1] = new char[21]; // similar
cin >> Months[0]; // Reads into the bytes starting at the one whose
// address is in Months[0], the input characters
cin >> Months[1]; // similar
cout << Months[0] << "\n"; // outputs the characters starting with the
// one whose address is in Months[0]; keeps going till the null byte.
cout << Months[1] << "\n"; // similar
delete [] Months[0]; // release the space pointed to by Months[0]
delete [] Months[1]; // similar
return 0;
}
I compiled it and ran it as follows:
xi 121 > g++ t1.cpp
xi 122 > a.out
jan
feb
jan
feb
The first two "jan" and "feb" lines were my input; the next two were
the output.
Next, I added the line:
Months[0][1] = 0; Months[1][1] = 0;
immediately following the second input command and compiled and ran
it again. Here is what I got:
xi 123 > g++ t1.cpp
jxi 124 > a.out
jan
feb
j
f
See if you can explain why.
--Neelam.