Page 1 of 1

Pointers to structs / Problems ?

Posted: Sat Aug 28, 2004 5:27 pm
by POedBoy
Hi all,

I'm unsure whether this is a bug with pb or just me doing something stupid...I'm returning the address of a structure from a procedure. A couple issues arise.

With the debugger on, I seem to be getting garbage values within its member fields. With it off, things seem to be okay... ( on another note, the debugger wont work with #PB_Any either soo I'm guessing the debugger needs some debugging :) ? )

Now, even with the debugger off, I can usually only read 1 value from the structure. Everything after returns garbage.

Heres the test code I was using in an attempt to figure out whats going on:

Code: Select all

Structure Person
    Age.l
    Name.s
EndStructure

Procedure.l NewPerson(Name.s,Age.l)
    Protected This.Person
    This\Name=Name
    This\Age=Age
    ProcedureReturn @This.Person
EndProcedure

Procedure Test(*This.Person)
    MessageRequester("Testing..",*This\Name, #PB_MessageRequester_Ok)
EndProcedure

;================================================
OpenConsole()


*SomeDude.Person = NewPerson("Bob",26)

PrintN(*SomeDude\Name)
PrintN(Str(*SomeDude\Age))

PrintN(*SomeDude\Name)
PrintN(Str(*SomeDude\Age))

;Test(SomeDude.Person)
;Test(SomeDude.Person)

Input()

The first value (in this case, *SomeDude\Name) is right-- everything after goes to hell.

Its like the pointer is dying or moving somehow (?!?). Am I doing something wrong here?

Posted: Sat Aug 28, 2004 5:32 pm
by Bonne_den_kule
Use Static instead of protected variable

Posted: Sat Aug 28, 2004 5:44 pm
by POedBoy
Thanks for the quick reply :D

That solves the garbage issue but creates a new one--- with static (or shared) it keeps referencing the same structure over and over... how can I instantiate new structs within the same procedure? Would i have to use an array or list?

Posted: Sat Aug 28, 2004 9:35 pm
by GedB
POedBoy,

There are two main ways for doing this: Using a linked list or allocating memory directly.

Purebasic has built in linked lists that are alway global. Read more about them here:

http://www.purebasic.com/documentation/linkedlist/

You're procedure would add an element to the linked list and then return a pointer to that element.

You can see some code of mine using this technique here: viewtopic.php?t=8538

Alternatively you can allocate the memory yourself directly. Allocate memory that is the right size for you're structure then assign a pointer to that.

Use the SizeOf command to find out the size of your structure. Docs here:
http://www.purebasic.com/documentation/

The documentation for using memory direct is here:
http://www.purebasic.com/documentation/ ... emory.html
http://www.purebasic.com/documentation/ ... index.html

Here's an example of mine using this technique:
viewtopic.php?t=10319&postdays=0&postor ... t&start=20

I would recommend the first approach, using Linked List, until you have more experience.