array of stuctures and pointers

Hello,I seem to be having some difficulty trying to create a pointer for a struct (which is an array of structs),

struct prices
{
string item;
int cost;
};

prices set[5]; //create 5 structs of above

//After initialising the data, i try the following;


prices *ptr = &set;


The error I get is

1>c:\users\d\desktop\cpu science\17\pointerstructfunctiontest\pointerstructfunctiontest\pointerstructfunctiontest.cpp(47) : error C2440: 'initializing' : cannot convert from 'prices (*__w64 )[5]' to 'prices *'


I know this is the way to declare pointer to a single struct, but obviously not with an array of structs. Any help would be appreciated, thanks
All arrays are pointers, so set is already a prices *. There's no need to create a pointer to set[0].
If, for any reason, you need another pointer, just do
prices *p=set;
Likewise, you can pass the pointer to a function declared as
void f (prices *array,int size);
by calling
f(set,5);
f() has, then, access to all elements in the array:
1
2
3
4
void f(prices *array,int size){
    for (int a=0;a<size;a++)
        std::cout <<array[a].item<<std::endl;
}
Last edited on
And as this is beginner C++, I would avoid the use of the name "set" as the standard library has a set container type and folks around here seem to always use "using namespace std;" in their code.
The fact that he used string and not std::string does seem to indicate that.
Ive renamed set to sett anyway now

I kind of know what you mean helios, with arrays being almost like constant pointers, but anyway

What i wanted to know was,

how can i have / declare a single pointer to point to different items different array of struct, e.g.


-the pointer shows the contents of struct[1].cost ,

or, the pointer shows the contents of struct[3].item
anyone?
Do you need a pointer that can point to either of the members of the struct, or that can point to the struct itself?
To the members of the struct, but since we have an array of structs, im not sure how to do this
Since the members are of different types, you can't use a regular pointer. You need a generic pointer: void *
1
2
3
4
5
void *p=(void *)&(array[i].item);
string a=*(string *)p;

p=(void *)&(array[i].cost);
int b=*(int *)p;


I think what you really need, though, is a pointer to the struct itself, which you already have in the form of an array.
Last edited on
Topic archived. No new replies allowed.