Pointer To Pointer Question

New to FreeBASIC? Post your questions here.
Post Reply
nimdays
Posts: 236
Joined: May 29, 2014 22:01
Location: West Java, Indonesia

Pointer To Pointer Question

Post by nimdays »

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
Moderator
Posts: 12576
Joined: Apr 22, 2009 12:46
Location: Paris suburbs, FRANCE

Re: Pointer To Pointer Question

Post by fxm »

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: 8267
Joined: Jan 10, 2006 20:30
Location: Scotland

Re: Pointer To Pointer Question

Post by dodicat »

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: 236
Joined: May 29, 2014 22:01
Location: West Java, Indonesia

Re: Pointer To Pointer Question

Post by nimdays »

Thank you both
Post Reply