C
ctj951
I have a very specific question about a language issue that I was
hoping to get an answer to. If you allocate a structure that
contains
an array as a local variable inside a function and return that
structure, is this valid?
As shown in the code below I am allocating the structure in the
function and then returning the structure. I know if the structure
contained only simple types (int, float) this will work without
problems as you are getting a copy of those items returned from the
function. But I'm wondering with an array which is being returned
from the function as part of the structure is a pointer to the local
variable or perhaps a copy of that array (as it would be for simple
types). I think we might be getting a pointer returned but I'm not
sure.
#include <stdio.h>
struct Item
{
int itemNumber;
int internalItems[5];
};
struct Item CreateItem()
{
struct Item newItem;
newItem.itemNumber = 10;
newItem.internalItems[ 0 ] = 1;
newItem.internalItems[ 1 ] = 2;
newItem.internalItems[ 2 ] = 3;
newItem.internalItems[ 3 ] = 7;
newItem.internalItems[ 4 ] = 9;
return( newItem );
}
void PrintItem( struct Item iItemToPrint )
{
printf( "%d", iItemToPrint.internalItems[0] );
}
int main ()
{
struct Item testItem = CreateItem();
PrintItem( testItem );
return 0;
}
This is a specific question about a specific language issue. Thank
You.
hoping to get an answer to. If you allocate a structure that
contains
an array as a local variable inside a function and return that
structure, is this valid?
As shown in the code below I am allocating the structure in the
function and then returning the structure. I know if the structure
contained only simple types (int, float) this will work without
problems as you are getting a copy of those items returned from the
function. But I'm wondering with an array which is being returned
from the function as part of the structure is a pointer to the local
variable or perhaps a copy of that array (as it would be for simple
types). I think we might be getting a pointer returned but I'm not
sure.
#include <stdio.h>
struct Item
{
int itemNumber;
int internalItems[5];
};
struct Item CreateItem()
{
struct Item newItem;
newItem.itemNumber = 10;
newItem.internalItems[ 0 ] = 1;
newItem.internalItems[ 1 ] = 2;
newItem.internalItems[ 2 ] = 3;
newItem.internalItems[ 3 ] = 7;
newItem.internalItems[ 4 ] = 9;
return( newItem );
}
void PrintItem( struct Item iItemToPrint )
{
printf( "%d", iItemToPrint.internalItems[0] );
}
int main ()
{
struct Item testItem = CreateItem();
PrintItem( testItem );
return 0;
}
This is a specific question about a specific language issue. Thank
You.