0

there have been a lot of resources on this but I could not really understand the concept of this.

Here is my attempt using pointers:

struct PEOPLE{
   int id;
   string name;
   float cash;
};

int main(){
   PEOPLE data[5];
   getdata(data);

   for(int i = 0; i < 5; i++){
      cout << data[i].id << " " << data[i].name << "  " << data[i].cash;
   }
   return 0;
}

void getdata(PEOPLE &*refdata[5]){
    refdata[0].id = 11;
    refdata[0].name = "John Smith";
    refdata[0].cash = 200.30;
    //and so on for index 1,2,3,4
}

Is this approach correct, I doubt it will work.

1
  • Shouldn't the structure definition end with a semicolon? Commented Dec 1, 2013 at 8:47

2 Answers 2

1

This would work for arrays of a size known at compile time:

template<size_t N >
void getdata(PEOPLE (&refdata)[N] )
{
   refdata[0] = ....;
}

To restrict to size 5,

void getdata(PEOPLE (&refdata)[5] )
{
   refdata[0] = ....;
}
Sign up to request clarification or add additional context in comments.

16 Comments

@edward That happens to be the required syntax for passing a (non-const) reference to a fixed size array. I must admit that doesn't make much sense to me, but the idea is to distinguish between a reference to an array and an array of references.
thanks for your help, one more q, when i pass by reference, should I do like this getdata(data); or this getdata(data[5]);?
@edward Use getdata(data);. getdata(data[5]) passes a single (invalid) element to the function. It is actually an out of bounds array access.
But the question still remains: why would you ever do this? Arrays already decay into pointers; passing by reference doesn't bring much benefits, and it just causes confusion...
@H2CO3 because it restricts it to a certain size, and you don't have to pass the size as a second parameter (second case), and it gives you a handle on the size in the function template case. It is making use of compile-time information lost when an array is allowed to decay into a pointer.
|
0

You can simply define it as:

void getdata(PEOPLE refdata[])

and call:

 getdata(data);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.