I have a struct that i want to return from a function, but i think it is a bit inefficient to return a really big struct, so i want to return its pointer.
Can i create the struct variable inside the function and then return its pointer, or would the pointer be dangling and left leading to nothing.
//Struct to hold a bmp of a font and information about it, offsets always start from 32 ( space in ascii )
typedefstruct
{
//This is the actual bitmap of ascii characters that we will blit from
SDL_Surface* bmp;
//The array that holds all the symbols, the array size is 94 to go from ascii space ( 32 ) to the tidle ( 126 )
struct symbol[94];
} font;
font* loadFont ( char* fileName )
{
font returnStruct;
//Blah blah load struct stuff, struct.blah = 1
//--Am i doing this right?--
return &returnStruct;
}
How would i approach this?
Also, would i be able to modify a function argument, is there anything wrong with that?
So if created the struct variable outside of the function ( in main ) and then passed it as an argument, which was a pointer, then i modify that?
Never return the address of automatic storage. The safer option is to make a static pointer within the function and return that instead.
1 2 3 4 5 6
Font *LoadFont( char *FileName_ )
{
static Font *Font_;
// Load the font...
return( Font_ );
}
This has it's drawbacks, but does ensure that "Font_" remains valid until the program ends. With each call to the function, the address pointed-to by "Font_" can change. This is the safest way of returning the address of storage that's declared within a function's scope. Note that static storage declared within a function scope remains even if the function is not currently being executed.
Your loadFont method should probably be a member function of the font struct.
1 2 3 4 5 6 7 8 9 10 11 12 13 14
//Struct to hold a bmp of a font and information about it, offsets always start from 32 ( space in ascii )
typedefstruct
{
//This is the actual bitmap of ascii characters that we will blit from
SDL_Surface* bmp;
//The array that holds all the symbols, the array size is 94 to go from ascii space ( 32 ) to the tidle ( 126 )
struct symbol[94];
void loadFont ( char* fileName )
{
//Blah blah load struct stuff, struct.blah = 1
}
} font;
@darkestfright: from the loadFont function that i would put in the typedef struct, how would i access the variables inside the struct ( i.e bmp and symbol )
EDIT: ive tried various things by putting the function inside the typedef, but it gives me errors, i dont know how to do this, can someone show me please? many thanks
EDIT2: dont worry, im writing in pure C, not C++, so it doesnt like that, ill just make functions outside of the typedef, thanks for your help