Passing an array of structs to a function
I have the following code. I have a method called SendBookDiffs(MTBookDiff *bookdiffs, UINT bookdiffs_total) which I would like to use. The description for this method is "This method accepts array of MTBookDiff structures, counting 'bookdiffs_total' elements."
So what I have tried is the following:
MTBookDiff *bookdiffs;
MTBookItem items[128];
bookdiffs->items = it开发者_高级运维ems;
But I encountered a "error C2106: '=' : left operand must be l-value" error. According to some replies, I have tried
memcpy(bookdiffs->items, items, sizeof(bookdiffs->items));
But is there the proper way of executing it? Thanks! Edited: Simplifying the question asked.
Based on the
#define MAX_PATH 260
enum EnMTAPIConstants
{
MT_SYMBOL_LEN =32,
MT_BOOK_DEPTH =32,
MT_ADDRESS_LEN =64,
MT_NEWSUBJECT_LEN =256,
MT_NEWSCATEGORY_LEN =256,
MT_LOGIN_LEN =64,
MT_PASSWORD_LEN =64,
MT_PARAMS_LEN =256,
MT_DESCRIPTION_LEN =MAX_PATH
}
struct MTBookItem
{
enum EnBookItemType
{
ItemReset=0,
ItemSell =1,
ItemBuy =2
};
UINT type;
double price;
INT64 volume;
UINT reserved[8];
};
struct MTBookDiff
{
wchar_t symbol[MT_SYMBOL_LEN];
MTBookItem items[MT_BOOK_DEPTH*4];
UINT items_total;
UINT reserved[64];
};
MTBookDiff *bookdiffs;
MTBookItem items[128];
bookdiffs->items = items;
you can't assign an array to another array as you do.
instead since you are anyway using C++, use vector
vector<MTBookItem> items
You need to distinguish between a[] and *a. The first allocated a block of memory big enough to hold the specified number of elements, leaving the variable pointing at the first. The second is just a pointer, which doesn't necessarily point at anything yet and which can be repointed elsewhere.
At risk of using an unpopular notation, Hungarian notation strictly distinguishes between ax
and px
, where the former is an array and the latter is a pointer. What's confusing is that you can pass ax
to a function taking px
, in which case the parameter is a pointer that is initialized to the first element of ax
. However, while you can assign a pointer a new value, you can't do that for an array.
You need to do one of the following:
memcpy(bookdiffs->items, items, sizeof(bookdiffs->items)
- change the type of the
items
fields fromMTBookItem items[]
toMTBookItem *items
.
EDIT
Given that this is a C++ question, using a std::vector
as others have suggested is almost certainly better than either of my two suggestions.
精彩评论