Returning struct from functions syntax in VC++
-
Could anybody point me to a basic source of information on using struct in functions - passing as parameters and returning from functions. I am confused regarding the difference in C an C++ syntax. I am looking for using arrays of struct. Thanks for your time Vaclav
-
Could anybody point me to a basic source of information on using struct in functions - passing as parameters and returning from functions. I am confused regarding the difference in C an C++ syntax. I am looking for using arrays of struct. Thanks for your time Vaclav
Passing arrays is the hard bit, a struct is just like a class, you can pass it in and you can pass it out. If I wanted to return an array of items, I'd probably take a std::vector by reference, and add them to that. Christian Graus - Microsoft MVP - C++
-
Could anybody point me to a basic source of information on using struct in functions - passing as parameters and returning from functions. I am confused regarding the difference in C an C++ syntax. I am looking for using arrays of struct. Thanks for your time Vaclav
Structs are typically passed by pointer. In the case of struct arrays, it really depends on how you allocate the array. By incrementing a struct pointer, you actually increment the pointer to point to the next struct (the compiler increments it by the sizeof() the struct). EX:
typedef struct _MyStruct
{
int iValue;
char caData[21];
} MyStruct;MyStruct *StructFcn(MyStruct *spStruct, int iCount);
void PassStructToFcn()
{
MyStruct *spRetval = NULL;
MyStruct sStruct;sStruct.iValue = 7;
strcpy(sStruct.caData,"Hello");spRetval = StructFcn(&sStruct,1);
}void PassStructArrayToFcn()
{
MyStruct *spRetval = NULL;
MyStruct sStruct[3]; // array of 3 structssStruct[0].iValue = 2;
strcpy(sStruct[0].caData,"Hello");
sStruct[1].iValue = 3;
strcpy(sStruct[1].caData,"Hello");
sStruct[2].iValue = 7;
strcpy(sStruct[2].caData,"Hello");spRetval = StructFcn(&sStruct[0],3);
}MyStruct *StructFcn(MyStruct *spStruct, int iCount)
{
// find the struct who's value is 7
for (int iLup = 0; iLup < iCount)
{
if (spStruct->iValue == 7)
return spStruct;spStruct++; }
return NULL;
}onwards and upwards... -- modified at 12:58 Monday 12th December, 2005