pointing to an array

Posted By: PrenceOfDarkness

pointing to an array - 04/25/08 06:51

I never would have thought I'd ever have to do something like this, but I guess the time has come and I can't seem to figure it out. Before you tell me to pick up a C++/C book let me say I've already tried that but they don't really explain it to clearily.

How do I point to an array? How would I then pass that pointer on to a function? I'd assumed it's just like every other pointer but I'm having problems. How can I change different array values using the pointer?

If you could give examples using the "var" variable type it would great.
If anyone knows a text I can find all theses answers in please let me know.
Posted By: Joey

Re: pointing to an array - 04/25/08 08:38

you're asking for two different things. pointers to arrays are, as arrays are in c nothing else but pointers to the first array element, pointers to pointers, e.g. var**. to pass an array, you don't need a pointer to the array but you can pass the array as-is, since it is already a pointer to the first array element, e.g. var*.

 Code:
var array[200]; // now array is a pointer to the first element of 200 allocated vars on the stack
var* array2 = array; // array2 can be accessed just like array
var test = array[5];
test = array2[5];

var** p_array = &array; // now you're pointing to a pointer to the first element
test = (*p_array)[5]; // you have to dereference it first, the following is also valid, but no good style and i'm not sure lite-c compiles it
test = p_array[0][5]; // #1 see below

...

void f(var* arr)
{
    var t = arr[5]; // keep care of your array bounds
}
void g(var** arr)
{
    var t = (*arr)[5]; // same as above, hope you get the idea
}

...

f(array);
f(array2);
f(*p_array);
g(&array);
g(&array2);
g(p_array);


multidimensional arrays lift the pointer level up accordingly, as twodimensional arrays are nothing else than pointers to pointers (see here #1).

joey.

btw. there are actually some differences. compilers usually allocate and deallocate pointers and arrays differently. so let's call them compatible here since we can use them both the same way.
Posted By: PrenceOfDarkness

Re: pointing to an array - 04/26/08 04:31

wow... you made it so simple that I feel now like a total noob for even asking! You have no idea how much you just helped me and my game out! THANKS A MILLION!
© 2023 lite-C Forums