Pointer To Pointer Question

New to FreeBASIC? Post your questions here.
nimdays
Posts: 226
Joined: May 29, 2014 22:01
Location: ID

Pointer To Pointer Question

Postby nimdays » May 21, 2020 4:33

Hello, Do you think below is safe without allocating first?

Code: Select all

type node
    as node ptr pnext
end type

dim as node ptr proot,ptail

proot = new node
ptail = new node
proot->pnext = ptail

dim as node ptr ptr p = @proot

p[1] = ptail '' this

?*p & " " & *(p+1)
?proot & " " & ptail

delete proot
delete ptail

sleep

fxm
Posts: 9558
Joined: Apr 22, 2009 12:46
Location: Paris suburbs, FRANCE

Re: Pointer To Pointer Question

Postby fxm » May 21, 2020 5:20

Your code is not safe because there is no evidence that valid memory is allocated at 'p[1]'.
'dim as node ptr proot, ptail' does not necessarily always produce 2 contiguous allocations in memory, and even if this were the case, the allocation order (between 'proot' and 'ptail') may depend on the platform.

A solution (among the possible ones) to ensure 2 contiguous allocations in memory:

Code: Select all

type node
    as node ptr pnext
end type

type nodeptrs  '' to ensure that .proot and .ptail are contiguous in memory
    as node ptr proot
    as node ptr ptail
end type

dim as nodeptrs pp

pp.proot = new node
pp.ptail = new node
pp.proot->pnext = pp.ptail

dim as node ptr ptr p = @pp.proot  '' or p = @pp

?p[0] & " " & p[1]
?pp.proot & " " & pp.ptail

delete pp.proot
delete pp.ptail

sleep
dodicat
Posts: 6370
Joined: Jan 10, 2006 20:30
Location: Scotland

Re: Pointer To Pointer Question

Postby dodicat » May 21, 2020 7:39

You could use your own memory slots held in a static array.
No need for new (which is not contiguous in memory) or delete.

Code: Select all


type node
    as node ptr pnext
    static as node memslot(1 to 10) 'create number of slots to suit needs, automatically contiguous.
end type

dim as node node.memslot(1 to 10)=any 'activate slots (any =without any construction, optional)

dim as node ptr proot,ptail

proot=@node.memslot(1)   'pick off slots
ptail=@node.memslot(2)

proot->pnext = ptail

dim as node ptr ptr p = @proot

p[1] = ptail '' this

?*p & " " & *(p+1)
?proot & " " & ptail


sleep
 
nimdays
Posts: 226
Joined: May 29, 2014 22:01
Location: ID

Re: Pointer To Pointer Question

Postby nimdays » May 21, 2020 9:12

Thank you both

Return to “Beginners”

Who is online

Users browsing this forum: No registered users and 3 guests