Sambar Server Documentation
|
CScript Pointers and Arrays |
The following example contains a pointer to an integer. We assign to our
pointer the address (&) of an integer, and then modify the data stored there.
|
When run, the value of number is incremented, even those we never added to number directly. Instead, we changed the value stored at the memory address shared by number, thereby indirectly modified it. Unlike C, CScript prevents you from declaring a pointer and assign it to an invalid memory address. All pointer references are tested for validity prior to allowing their use (preventing users from overwriting data belonging to some other variable or piece of code).
printf ("%s\n", mystring);
you are actually passing
as a parameter the address of a sequence of characters.
|
When run, the program prints the words "Hello there!"
to screen,
followed again by a second "there!"
. There are two print
statements, one for mypointer, and another for mypointer + 6.
Since a pointer is just a memory address, we can add to this address
just like any other number. Remember though that in C, arrays are
indexed starting at zero (0).
The following initializes an array containing 6 integers:
int my_array[] = { 43, 22, 25, 5, -5, 100 };
Each of the integers can be referred to by means of a subscript to
my_array, i.e. using my_array[0] referrs to the integer 43.
Since CScript allows arbitrary types to be stored in arrays, the array
definition can include strings, for example:
aa = "Test String";
my_array[] = { 43, "test", NULL, 5.5, -5, aa };
Local arrays (e.g. declared within a function) are allocated at runtime
and may have variable indexes as the following example illustrates:
int x = 12;
string arraystr[++x]; // arraystr holds 13 elements
int arrayint[x * 2]; // arrayint holds 26 elements
printf("arrayint holds %d elements.\n", sizeof(arrayint));
© 2001 Sambar Technologies. All rights reserved. Terms of Use.