Pointer to a struct type

Hey guys , I was just wondering if I wanted to create a dynamic struct like 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
28
29
30
31
#include<iostream>
#include<iomanip>
using namespace std;
struct candy{
	char x[20];
	double y;
	int z;
};

int main(){


	candy *ptr = new candy[3];

	cin.getline(ptr[0].x, 20);

	cin >> ptr[1].y;
	
	cin >> ptr[2].z;

	cout << ptr[0].x << endl;

	cout << ptr[1].y << endl;
	cout << ptr[2].z << endl;

	delete ptr;

	getchar();
	getchar();
	return 0;
}


this is a dynamic struct , this here:
candy *ptr = new candy[3];

should create 3 structs for type candy:

my question here:

1- this creates 3 struct that goes to the heap memory right ?
2- if I used:
candy *ptr[2] = new candy;
this would create two pointers that points to a type candy , right?

3- what I learned is that when you use a dynamic struct , you should access it's variables by using "->" operator , but when I tried to it gives me an error:

type 'candy' does not have an overloaded member 'operator ->'

why ? I know that there's another method to access it's variables but why won't this work ?
* by the way I'm only trying , so this is an example , I know that in every struct there's 3 variables , but I wanted to understand this , so I tried to access a variable at a time
1: Yes

2: No, this would put one candy object into ptr[ 2 ].

3: We need to see the exact error to be able to help you.
Thanks mate , I put the error , but here it is again :D

type 'candy' does not have an overloaded member 'operator ->'

this is the error , I didn't put the rest of the info because it doesn't matter " like where is the project " what file " "
closed account (Dy7SLyTq)
dont make it a pointer. just do candy ptr[3]. if you make it a pointer you need to use the class to pointer operator (->) instead of the direct access dot operator(.)
On which line do you get this error?
Note the difference:
1
2
3
4
  candy->blah;
(*candy).blah;
  candy[0].blah;
//candy[0]->blah; //error 
closed account (Dy7SLyTq)
well not to confuse her(him?), the last one is only an error in this case.
Thanks guys,

so if I wanted to access a dynamic array of struct I should use the dot operator ?
pointer->blah is a shortcut for (*pointer).blah, so you are always using the dot operator without realizing.

And before someone tries to contradict me, overloading operator-> requires the returned value to also overload operator->, so eventually at the end of the chain it has to be a raw pointer.
Last edited on
Topic archived. No new replies allowed.