Qbasicnews.com

Full Version: Pointers to functions
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I can't figure this out...
I make a pointer, and make a function return an address to this pointer.
This address returned to the pointer from the function is the start address to an array which contains some numbers.
First print goes ok, but second one gives something random.
I've also tried +2 and +4 on the second print statement without results.
And I've tried to make a simple integer variable, and let the function return its address to this variable, and then give the pointer the value of this integer.

Any ideas?

:-?


Code:
declare function MakeList ()

dim my_pointer as integer ptr

my_pointer = MakeList()

print *my_pointer
print *(my_pointer + 1)
sleep

function MakeList ()
    dim MyList(4) as integer
    MyList(0) = 5
    MyList(1) = 10
    MyList(2) = 20
    MyList(3) = 40
    MyList(4) = 80
    return @MyList(0)
end function
The problem is that you dim an array inside your function, but this array will be freed when the functions ends.

Try this:
Code:
declare function MakeList ()

dim my_pointer as integer ptr
dim shared MyList(4) as integer

my_pointer = MakeList()

print *my_pointer
print *(my_pointer + 1)
print *(my_pointer + 2)
print *(my_pointer + 3)
print *(my_pointer + 4)
sleep

function MakeList ()
    
    MyList(0) = 5
    MyList(1) = 10
    MyList(2) = 20
    MyList(3) = 40
    MyList(4) = 80
    return @MyList(0)
end function
Thanks 8)
this should work too:
Code:
declare function MakeList () as integer ptr

dim my_pointer as integer ptr

my_pointer = MakeList()

print *my_pointer
print *(my_pointer + 1)
sleep

function MakeList () as integer ptr
    dim MyList as integer ptr
    MyList = callocate( len( integer ) * 5 )
    MyList[0] = 5
    MyList[1] = 10
    MyList[2] = 20
    MyList[3] = 40
    MyList[4] = 80
    return MyList
end function