Question about Redim String

Started by Roland Stowasser, July 13, 2024, 10:56:07 AM

Previous topic - Next topic

0 Members and 1 Guest are viewing this topic.

Roland Stowasser

Hi Charles,

it seems to me that redim string(n) does not preserve contents if using in a  procedure? Is there a solution / workaround or am I doing simply something wrong?

Test_redim_string.o2bas:

uses console

cls
printl "Redim String Test in procedure"
printl
 
int count = 20
redim string dat(count)
printl "count = " count
dat(10) = "Hello" : dat(11) = "World!"
printl dat(10) " " dat(11) : printl
'dat(40) = "Goodbye!" // will crash, which is ok

count += 20
printl "count = " count
redim string dat(count)
dat(40) = "Goodbye!"
printl dat(10) " " dat(11) " " dat(40) : printl

sub Extend_dat(string dat(), int count)
printl "in Extend_dat procedure:"
printl "count = " count
printl dat(10) " " dat(11) " " dat(40) : printl
 
count +=20
printl "count = " count
redim string dat(count)
printl "dat(10,11,40) = ? " dat(10) " " dat(11) " " dat(40) : printl
end sub

Extend_dat(dat(), count)

printl "Enter ..." : waitkey


Charles Pegge

Hi Roland,

To pass all the redim attributes to a procedure, the array must be passed by reference with brackets containing redim

sub Extend_dat(string* dat(redim), int count)

Alternatively, because you have defined Dat in global space, you can omit it as a parameter, then the procedure will be operating directly on the global Dat

sub Extend_dat(int count)


Roland Stowasser

Thank you Charles. Passing an argument string *dat(redim) was new to me and it is brilliant! I changed the names and I also passed count  by reference and Extend_dat() is declared now:

sub Extend_dat(string *data(Redim), int *cnt)

For me this is very impressive. I just have to remember it.

Test_Redim_String(redim).o2bas:

uses console

cls
printl "Redim String Test in procedure"
printl
 
int count = 20
redim string dat(count)
printl "count = " count
dat(10) = "Hello" : dat(11) = "World!"
printl dat(10) " " dat(11) : printl
'dat(40) = "Goodbye!" // will crash, which is ok

count += 20
printl "count = " count
redim string dat(count)
dat(40) = "Goodbye!"
printl dat(10) " " dat(11) " " dat(40) : printl

sub Extend_dat(string *data(Redim), int *cnt)
  printl "in Extend_dat procedure:"
  printl "cnt = " cnt
  printl data(10) " " data(11) " " data(40) : printl
 
  cnt +=20
  printl "cnt = " cnt
  redim string data(cnt)
  data(60) = "See you later!"
  printl data(10) " " data(11) " " data(40) " " data(60) : printl
end sub

Extend_dat(dat(), count)

printl "After Extend_dat procedure:"
printl "count = " count
printl dat(10) " " dat(11) " " dat(40) " " dat(60)
printl

printl "Enter ..." : waitkey