question about pointer and dynaminc memory

why i can't write code like this:"int* p[]=new int*[3]"
and must write" int* p;p=new int[3];"
sorry my english not very will,i hope you can read it.
thanks for help.
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
28
29
30
31
#include<iostream>
#include<string>
struct CandyBar
{
	std::string candyName;
	float weight;
	int colory;
};
int main()
{
	CandyBar* p= new CandyBar [3];
	//CandyBar* p[] = new CandyBar[3]; why this is fault?
	p[0].candyName = "a";
	p[0].weight = 1.1;
	p[0].colory = 11;

	p[1].candyName = "b";
	p[1].weight = 2.2;
	p[1].colory = 22;

	p[2].candyName = "c";
	p[2].weight = 3.3;
	p[2].colory = 33;

	std::cout << p[0].candyName << "/t" << p[0].weight << "/t" << p[0].colory << std::endl;
	std::cout << p[1].candyName << "/t" << p[1].weight << "/t" << p[1].colory << std::endl;
	std::cout << p[2].candyName << "/t" << p[2].weight << "/t" << p[2].colory << std::endl;

	system("pause");
	return 0;
}
new CandyBar[3]

This will create an array of 3 'CandyBar' objects. It will then return a pointer to the first element in that array.

Therefore the expression evaluates to this type: CandyBar*

CandyBar* p= new CandyBar [3];
This works because you are assigning that 'new' expression to 'p', which is of type CandyBar*. The type matches, therefore it is legal.


CandyBar* p[] = new CandyBar[3];
This does not work because you are assigning that expression to an array and not a pointer.

It's like doing this: int foo[] = 6; it doesn't make sense -- you can't assign a singular value to a whole array.
Topic archived. No new replies allowed.