I am working on a program in C and using the SDCC compiler for a 8051 architecture device. I am trying to write a function called GetName that will read 8 characters from Flash Memory and return the character array in some form. I know that it is not possible to return an array in C so I am trying to do it using a struct like this:
//********************FLASH.h file*******************************
MyStruct GetName(int i); //Function prototype
#define NAME_SIZE 8
typedef struct
{
char Name[NAME_SIZE];
} MyStruct;
extern MyStruct GetName(int i);
// *****************FLASH.c file***********************************
#include "FLASH.h"
MyStruct GetName( int i)
{
MyStruct newNameStruct;
//...
// Fill the array by reading data from Flash
//...
return newNameStruct;
}
I don't have any references to this function yet but for some reason, I get a compiler error that says "Function cannot return aggregate." Does this mean that my compiler does not support functions that return structs? Or am I just doing something wrong?
Yes, functions can return structs in C. Your code above has several errors. With a few changes, It compiles correctly under gcc (I don't have sdcc installed to try with, but please try the code below.
SDCC doesn't support assignment and returning structs yet (if their Wiki is up-to-date):
Maybe you should make a
function instead.
That said, you should put the function prototype before the
main
and after theMyStruct
. If there's no prototypes a function will be assumed to returnint
.(Also, the
main
function should be anint main(void)
orint main(int argc, char** argv)
. It shouldn't returnvoid
.)I really wouldn't want to use a C compiler that didn't implement structure call and return by value, as KennyMT suggests yours doesn't. In fact, such a compiler should not really be called a C compiler. If the compiler implements structures at all, return by value is not hard to implement.
Anyway, to work with your compiler you will want something like:
All post-ANSI C89/90 compilers allow returning struct objects. Classic (pedantic) K&R C compilers do not.
However, in any case you have to declare the function first. i.e. before you call it. And
char[8] Name
inside your struct is not a valid declaration. The valid form ischar Name[8]
.Your pointer-to-array-returning function is declared correctly. It is your size macro that's broken. Should be
Note: no
=
character.