Help with Dynamic Arrays

I am having problems with an assignment using a dynamic array of chars and pointers. I am supposed to create a dynamic array, fill the array using pointers, and then delete the array. Every time I run the code below, I get a Heap Corruption error. Could anybody point me to what I am doing wrong?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
 const int MAXNAME = 10;
	int pos;
	char * title;

	title = new char(MAXNAME);

	cout << "Enter a title with exactly 10 characters." << endl;

	for (pos = 0; pos < MAXNAME; pos++)
		*(title + pos) = cin.get();

	cout << "The title is ";
	for (pos = 0; pos < MAXNAME; pos++)
		cout << *(title + pos);

	cout << endl;

	delete[] title;
line 5 should be title = new char[MAXNAME]; (square brackets instead of parentheses). I'm surprised that it would compile as written.
closed account (48T7M4Gy)
Your code runs well here:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>

using std::cout;
using std::cin;
using std::endl;

int main()
{
  const int MAXNAME = 10;
	int pos;
	char * title;

	title = new char(MAXNAME);

	cout << "Enter a title with exactly 10 characters." << endl;

	for (pos = 0; pos < MAXNAME; pos++)
		*(title + pos) = cin.get();

	cout << "The title is ";
	for (pos = 0; pos < MAXNAME; pos++)
		cout << *(title + pos);

	cout << endl;

	delete[] title;
}



Enter a title with exactly 10 characters.
what to do
The title is what to do
 
Exit code: 0 (normal program termination)


(Why the shell compiler doesn't pick up the round bracket error is a mystery.)
Last edited on
Geez, I can't believe I missed that. That fixed the problem. I wish it hadn't compiled, I probably would have found the problem sooner. Thanks for the help!
closed account (48T7M4Gy)
Mystery solved

http://www.cplusplus.com/forum/beginner/151620/
Last edited on
Topic archived. No new replies allowed.