Re: Returning a struct from a function - strange behavior
- From: CBFalconer <cbfalconer@xxxxxxxxx>
- Date: Tue, 07 Oct 2008 19:12:22 -0400
DiAvOl wrote:
#include <stdio.h>
typedef struct person {
char name[40];
int age;
} Person;
static Person make_person(void);
int main(void) {
printf("%s\n", make_person().name);
return 0;
}
static Person make_person(void) {
static Person p = { "alexander", 18 };
return p;
}
The above small program when compiled without the -std=c99 option
(using gcc 4.2.3) gives me a warning:
"warning: format ?%s? expects type ?char *?, but argument 2 has
type ?char[40]?"
and also fails with a segmentation fault when executed.
If I replace the line printf("%s\n", make_person().name); with
printf("%s\n", &make_person().name[0]); everything works as
expected.
Why does this happen? Isn't make_person().name a pointer to the
array's first element?
No. make_person() returns a struct by value, which has a field
identified by .name. That field is an array of 40 chars. It is a
portion of the return struct, which has never been put in
accessible memory.
Your alleged 'good' experience with lcc shows a bug in lcc. I
don't know if you mean lcc-win32 (which has quite a few known
insects) or lcc (which is less well known here).
--
[mail]: Chuck F (cbfalconer at maineline dot net)
[page]: <http://cbfalconer.home.att.net>
Try the download section.
.
- Follow-Ups:
- Re: Returning a struct from a function - strange behavior
- From: Keith Thompson
- Re: Returning a struct from a function - strange behavior
- From: Martien Verbruggen
- Re: Returning a struct from a function - strange behavior
- From: Peter Nilsson
- Re: Returning a struct from a function - strange behavior
- References:
- Prev by Date: Re: EARN 1000$ IN EVERY MONTH
- Next by Date: Re: Returning a struct from a function - strange behavior
- Previous by thread: Re: Returning a struct from a function - strange behavior
- Next by thread: Re: Returning a struct from a function - strange behavior
- Index(es):
Relevant Pages
|