473,836 Members | 1,560 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Returning an array inside a structure that was allocated within afunction

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.itemNum ber = 10;
newItem.interna lItems[ 0 ] = 1;
newItem.interna lItems[ 1 ] = 2;
newItem.interna lItems[ 2 ] = 3;
newItem.interna lItems[ 3 ] = 7;
newItem.interna lItems[ 4 ] = 9;
return( newItem );
}

void PrintItem( struct Item iItemToPrint )
{
printf( "%d", iItemToPrint.in ternalItems[0] );
}

int main ()
{
struct Item testItem = CreateItem();
PrintItem( testItem );
return 0;
}

This is a specific question about a specific language issue. Thank
You.
Nov 13 '08 #1
5 2682
ctj951 <ch************ *****@yahoo.com writes:
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?
Yes. In fact, this is really the only way to return an array from a
function.
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.
Nope, the entire structure, including the array, gets copied (*). So you're
on firm ground here.

(*) Conceptually speaking. In practice, the compiler can do anything
that has the same effect. It might be able to merge the two copies into
one.
#include <stdio.h>

struct Item
{
int itemNumber;
int internalItems[5];
};

struct Item CreateItem()
{
struct Item newItem;
newItem.itemNum ber = 10;
newItem.interna lItems[ 0 ] = 1;
newItem.interna lItems[ 1 ] = 2;
newItem.interna lItems[ 2 ] = 3;
newItem.interna lItems[ 3 ] = 7;
newItem.interna lItems[ 4 ] = 9;
return( newItem );
}

void PrintItem( struct Item iItemToPrint )
{
printf( "%d", iItemToPrint.in ternalItems[0] );
}

int main ()
{
struct Item testItem = CreateItem();
PrintItem( testItem );
return 0;
}

This is a specific question about a specific language issue. Thank
You.
Nov 13 '08 #2
ctj951 wrote:
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?
Yes.
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.
No. The array is an array, not a pointer. It takes up actual space in
the local array, and gets copied along with the rest of the struct when
the 'return' statement is executed.
#include <stdio.h>

struct Item
{
int itemNumber;
int internalItems[5];
};

struct Item CreateItem()
{
struct Item newItem;
newItem.itemNum ber = 10;
newItem.interna lItems[ 0 ] = 1;
newItem.interna lItems[ 1 ] = 2;
newItem.interna lItems[ 2 ] = 3;
newItem.interna lItems[ 3 ] = 7;
newItem.interna lItems[ 4 ] = 9;
return( newItem );
}

void PrintItem( struct Item iItemToPrint )
{
printf( "%d", iItemToPrint.in ternalItems[0] );
}

int main ()
{
struct Item testItem = CreateItem();
The 'return' statement in CreateItem() causes the local new_item object
to be copied to the testItem. The contents of the array get copies along
with the rest of the struct.
PrintItem( testItem );
return 0;
}
Nov 13 '08 #3
James Kuyper wrote:
ctj951 wrote:
>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.

No. The array is an array, not a pointer. It takes up actual space in
the local array, and gets copied along with the rest of the struct when
the 'return' statement is executed.
Wow. I always assumed it was the other way around, but never tried it
in actual code. I guess you learn something new every day!
Nov 14 '08 #4
In article <88************ *************** *******@r36g200 0prf.googlegrou ps.com>,
ctj951 <ch************ *****@yahoo.com wrote:
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?
An array declared inside a struct has the same scope as the entire struct.
Anywhere you can use the struct, the array also exists.

--
I'm not even supposed to be here today.

I ASSURE YOU WE'RE OPEN!
Nov 14 '08 #5
ctj951 <ch************ *****@yahoo.com writes:
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.itemNum ber = 10;
newItem.interna lItems[ 0 ] = 1;
newItem.interna lItems[ 1 ] = 2;
newItem.interna lItems[ 2 ] = 3;
newItem.interna lItems[ 3 ] = 7;
newItem.interna lItems[ 4 ] = 9;
return( newItem );
}

void PrintItem( struct Item iItemToPrint )
{
printf( "%d", iItemToPrint.in ternalItems[0] );
}

int main ()
{
struct Item testItem = CreateItem();
PrintItem( testItem );
return 0;
}
This comes close to a topic that we had a lengthy discussion about
just recently.

There's no problem with the code you posted.

<DIGRESSION>
Well, there are a couple of minor things, but they're not relevant to
your question. The way to declare function with no parameters is
"(void)"; "()" indicates an unspecified number and type of parameters,
which is legal but IMHO not as good. <OT>In C++, empty parentheses do
indicate that the function has no parameters.</OTThe parentheses on
the return statement are unnecessary (but harmless). And you should
print a new-line at the end of your output.
</DIGRESSION>

But there's an issue that you could run into.

As others have pointed out, a function returning a structure returns
it by value; the result is a single value of type struct ITem,
consisting of the values of the itemNumber and internalItems members.
There's no problem returning such a value from a function, assigning
it to an object or using to initialize an object, or passing it to
another function.

But if you tried to index the array member of the result directly, you
could run into problems.

For example, if you write:

printf("%d\n", CreateItem().in ternalItems[0]);

then something odd happens. CreateItem().in ternalItems is an
expression of array type. In most contexts, including this one, such
an expression is implicitly converted to a pointer to the first
element of the array object. The [0] indexing operator then extracts
the 0th element of that array object.

"What array object?", I hear you cry. Good question. The array is a
member of a struct *value*; there is no array object. But the C
standard says that there has to be an object. This is a hole in the C
standard, something that I suspect the authors just didn't think of at
the time. Different compilers may handle this differently; some
probably do handle it in such a way that it Just Works, but others
might not.

The workaround is simple: Don't directly index an array member of a
function result. Instead, save the returns struct value in an object
and use that to do the indexing, and you won't have to worry about
this issue.

The preliminary first draft of the C201X standard adds wording that
says an object of "temporary lifetime" is created in this case. Grab
a copy of n1336.pdf and see section 6.2.4 if you're really interested.

Incidentally, the form of your code makes me suspect that you're
actually working in C++. The difference doesn't affect the code you
posted (except perhaps for the meaning of the "()" in the function
declarations), but I think C++ handles the indexing glitch differently
(as I recall, a value returned from a function is treated as a
temporary object). If you care, ask in comp.lang.c++.

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
Nokia
"We must do something. This is something. Therefore, we must do this."
-- Antony Jay and Jonathan Lynn, "Yes Minister"
Nov 14 '08 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

9
3974
by: pvinodhkumar | last post by:
The number of elemets of the array, the array bound must be constant expression?Why is this restriction? Vinodh
4
4989
by: Anthony | last post by:
Hello, I am writing a function that populates an array of pointers to strings. Both the number of strings in the array, and the lengths of the strings, are dynamic; in particular, the number of strings won't be known until just before the function returns. The problem is that in the calling function, I need to know both the address of the array, and the number of strings. My first thought was to pass a pointer to the array into the...
8
3692
by: Peter B. Steiger | last post by:
The latest project in my ongoing quest to evolve my brain from Pascal to C is a simple word game that involves stringing together random lists of words. In the Pascal version the whole array was static; if the input file contained more than entries, tough. This time I want to do it right - use a dynamic array that increases in size with each word read from the file. A few test programs that make use of **List and realloc( List, blah...
1
2327
by: Guha | last post by:
I have a problem with returning a 2D array using a function which is called in main(). The piece of the code is given below. This is a test code only. #include"stdio.h" #include"alloc.h" void main() {
3
2850
by: Michel Rouzic | last post by:
It's the first time I try using structs, and I'm getting confused with it and can't make it work properly I firstly define the structure by this : typedef struct { char *l1; int *l2; int Nval; } *arrays; It's supposed to be a structure containing an array of chars, an array of ints and an int. I declare functions like this : arrays *parseline(char *line, int N)
8
2474
by: ulyses | last post by:
I'm trying to put pointer to flexible array of structures in other structure. I want to have pointer to array of pixels in screen structure. Here is mine code, but I think it isn't quite all right: struct pixel { int x; int y; int color; };
30
3362
by: questions? | last post by:
say I have a structure which have an array inside. e.g. struct random_struct{ char name; int month; } if the array is not intialized by me, in a sense after I allocated a
7
3171
by: Sam | last post by:
Hello I have a structure called Company. struct Company { char *employee; char *employee_address; }; I want to build an array of this structure but the number of employees will change thorughout the course the programs use so it will need to
4
2640
by: ctj951 | last post by:
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...
0
9671
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10846
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10551
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10594
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9376
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7793
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6979
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5828
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
4020
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.