[issue] string *p = new string

Hi, I have problem with this code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;

void main()
{
	int strings;
	cout << "number of strings: ";
	cin >> strings;
	string* p = new string[strings];
	for(int i = 1; i <= strings; i++)
	{
		cout << "string " << i << " info: ";
		cin >> p[i];
	}
        for(int i = 1; i <= strings; i++)
        {
                cout << p[i] << endl;
        }
	system("pause");
}


I'll get error when program is gonna cout strings, any suggestions?
indexes are zero based, not one based.

That is, the first element in your array is p[0] and the last is p[strings-1]

accessing p[strings] is stepping out of bounds of your array and is causing problems.

Take a look at your for loop:
1
2
// for(int i = 1; i <= strings; i++)  // <- bad, starts at 1, ends at 'strings'
for(int i = 0; i < strings; ++i)  // <- good, starts at 0, ends at 'strings-1' 


As a very general rule, when programming... start counting at 0, not at 1.
Topic archived. No new replies allowed.