Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
array assigned in SUBs
#1
ReDim and assign an array within a SUB and pass through the SUB's parameters 
.......
getarray z%()
print ubound(z%), z%(5)
end
SUB getarray( x() as integer)
n%= 25
ReDim as ineger x(0 to n%-1)
for p%= 0 to  n%-1
x%(p%)= p%*p%
next
end sub
Reply
#2
I just posted an example of this for you: https://qb64phoenix.com/forum/showthread.php?tid=1243&pid=16614#pid16614
Reply
#3
(06-11-2023, 03:10 AM)sivacc Wrote: ReDim and assign an array within a SUB and pass through the SUB's parameters 
.......
getarray z%()
print ubound(z%), z%(5)
end
SUB getarray( x() as integer)
n%= 25
ReDim as ineger x(0 to n%-1)
for p%= 0 to  n%-1
x%(p%)= p%*p%
next
end sub
Here is what I believe you are looking for:

Code: (Select All)
REDIM AS INTEGER x(0)

getarray x()
PRINT UBOUND(x), x(5)
END


SUB getarray (x() AS INTEGER)
    n% = 25
    REDIM AS INTEGER x(0 TO n% - 1)
    FOR p% = 0 TO n% - 1
        x(p%) = p% * p%
    NEXT
END SUB
New to QB64pe? Visit the QB64 tutorial to get started.
QB64 Tutorial
Reply
#4
Thanks Terry ! didnt know ReDim x(0) as Integer is ok ?
Reply
#5
(06-11-2023, 08:32 AM)sivacc Wrote: Thanks Terry ! didnt know ReDim x(0) as Integer is ok ?
You're welcome. Glad I could help.

DIM and REDIM will accept any index value(s) for an array. All legal:

DIM x(-1 TO 10) AS
DIM x(-100 TO -10) AS
DIM x(50 TO 100) AS
DIM x(1 TO 10, 50 TO 100) AS

All of the DIMs above could also be REDIM if you like for dynamic arrays.

When you declare an array with an index of 0 -> DIM x(0) <- you are actually creating an array with one value. Remember, QB64 and most other programming languages treat zero as a valid amount.

DIM x(0)
x(0) = 10

Many times I'll create dynamic arrays at the top of my code with a 0 index, such as for a ship firing bullets. As each bullet is fired I simply increase the size of the dynamic array to accommodate.

TYPE Type_Bullet
    x AS SINGLE        ' x coordinate of bullet
    y AS SINGLE        ' y coordinate of bullet
    vx AS SINGLE      ' x vector (travel)
    vy AS SINGLE      ' y vector (travel)
    Alive AS INTEGER ' is bullet still active? (true/false)
END TYPE

REDIM Bullet(0) AS Type_Bullet ' player bullet array



IF PlayerFiredBullet THEN '                                     did player fire bullet?
    REDIM _PRESERVE Bullet(UBOUND(Bullet) + 1) AS Type_Bullet ' increase the size of array while preserving data already contained within
    Bullet(UBOUND(Bullet)).x = ShipX '                    apply new bullet values
    Bullet(UBOUND(Bullet)).y = ShipY
    Bullet(UBOUND(Bullet)).vx = ShipVx
    Bullet(UBOUND(Bullet)).vy = ShipVy
    Bullet(UBOUND(Bullet)).Alive = -1
END IF

Here is the link to the wiki for DIM: https://qb64phoenix.com/qb64wiki/index.php/DIM
New to QB64pe? Visit the QB64 tutorial to get started.
QB64 Tutorial
Reply
#6
Got it !
Reply




Users browsing this thread: 1 Guest(s)