array of stuctures and pointers

May 11, 2009 at 7:50pm
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
May 11, 2009 at 7:57pm
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 May 11, 2009 at 8:00pm
May 11, 2009 at 8:01pm
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.
May 11, 2009 at 8:03pm
The fact that he used string and not std::string does seem to indicate that.
May 11, 2009 at 8:26pm
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
May 12, 2009 at 9:28am
anyone?
May 12, 2009 at 12:00pm
Do you need a pointer that can point to either of the members of the struct, or that can point to the struct itself?
May 12, 2009 at 12:02pm
To the members of the struct, but since we have an array of structs, im not sure how to do this
May 12, 2009 at 12:18pm
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 May 12, 2009 at 12:20pm
Topic archived. No new replies allowed.