how to make a procedure return a structure ?

Just starting out? Need help? Post your questions and find answers here.
BackupUser
PureBasic Guru
PureBasic Guru
Posts: 16777133
Joined: Tue Apr 22, 2003 7:42 pm

Post by BackupUser »

Restored from previous forum. Originally posted by pythagoras.

I've seen this example using pointers :

Structure WhatEver
Value1.b
Value2.l
EndStructure

Procedure GetIt()
Var.WhatEver
Var\Value1 = 5
ProcedureReturn @Var ; Return Pointer
EndProcedure

*NewVar.WhatEver = GetIt() ; get Result

Debug *NewVar\Value1


When i try to do the same thing with my code it always crash when the procedure return the @var (see code below). Anyone knows why ?

Thanks in advance,

yannis

--- code pasted
;-- create SITE type
Structure SITE
Id.b
Image.b
EndStructure

;-- create SECTOR type
Structure SECTOR
*Site1.SITE
*Site2.SITE
*Site3.SITE
Income.w
Owner.s
EndStructure

; Create the players array
Dim sector_array.SECTOR(7,7)


Global arboretum.SITE
arboretum\Id = 1
arboretum\Image = 1

arena.SITE
arena\Id = 2
arena\Image = 2

(etc...)


Procedure TranslateSite(i)

sit.SITE

Select i
Case 1
CopyMemory( @arboretum, @sit, SizeOf( SITE ) )
ProcedureReturn @sit
Case 2
(etc...)

EndSelect

EndProcedure

I then call translatesite this way :

sector_array(1,1)\site1 = TranslateSite(11)
BackupUser
PureBasic Guru
PureBasic Guru
Posts: 16777133
Joined: Tue Apr 22, 2003 7:42 pm

Post by BackupUser »

Restored from previous forum. Originally posted by tinman.
Originally posted by pythagoras

I've seen this example using pointers :

ProcedureReturn @Var ; Return Pointer
Whoever gave you that example should be removed from their computer :wink:

You cannot create a variable inside a procedure and then return a pointer to it since that variable does not exist after the end of a procedure.

Procedure variables are created on the stack and are destroyed after their use.

A correct example would be:

Code: Select all

Structure Whatever
  a.l
  b.l
EndStructure

MyVar.Whatever

Procedure MyProcedure(*blahblah.Whatever)
    *blahblah\a = 5
EndProcedure

MyProcedure(@MyVar)
--
It's not minimalist - I'm increasing efficiency by reducing input effort.
(Win98first ed. + all updates, PB3.51, Ed3.53)
BackupUser
PureBasic Guru
PureBasic Guru
Posts: 16777133
Joined: Tue Apr 22, 2003 7:42 pm

Post by BackupUser »

Restored from previous forum. Originally posted by pythagoras.
Originally posted by tinman

Whoever gave you that example should be removed from their computer :wink:
agreed :) !

Thanks for your help. There was another problem with my code though and i've found the solution in the meantime : the procedurereturn call was crashing because i was using a select in the procedure and forgot to use FakeEndSelect before returning the value.

thanks again !

Pythagoras
Post Reply