Advertisement

Passing arrays...

Started by January 30, 2000 04:02 PM
6 comments, last by Bucket_Head 24 years, 8 months ago
Ok, I should probably know how to do this, but I can''t seem to be able to get it to compile... Here''s my problem: I have a 2d character array which I want to pass into a function, and overwrite, from within that function. Any suggestions? Thanks for your time... - Ah, to write code; to compose electrical music, to manipulate the bits that make up everything...such is our chosen line of work. And for a game, no less!
- Hai, watashi no chichi no kuruma ga oishikatta desu!...or, in other words, "Yes, my dad's car was delicious!"
hm..maybe this will work, it has been awhile..

void main() {

char *array[32]

my_function(&array); // pass the address of the array.
//that is all it takes..i hope..

}

void my_function(char *array_to_change) {

array_to_change[what ever] = again_whatever;


}



-Syntax
-dieraxx@iname.com
-Lucas
Advertisement
If its an array that gets widely used you could typedef it and pass it as a type. I tend to do that a lot.
Is it just me, or are you passing a pointer to a pointer there?

my_function(&array);

You have to remember that the name of the array itself is a pointer to the start of the array, and therefore you don''t need the ''&'' address of operator.

my_function(array);

-Omalacon
An array is actually just a pointer to a block of memory, and the [] is just there so that you can convenientely access parts of that block of memory. For example, this:

char coolchar[32];

is the equivalent of this

char* coolchar = new char[32];

Both of these do the same thing, and elements in both are accessed in the same way (through using the [] operator). So basically, an array is really just a pointer to a block of memory.

So to pass an array you could do this:

void foo(char* string)
{
// do something with string
}

void main()
{
char testchar[32];

foo(testchar);
}

Easy enough, eh?

--TheGoop
quote: I have a 2d character array which I want to pass into a function, and overwrite, from within that function. Any suggestions?


void whatever( char *array, int dim1, int dim2 )
{
// do your thing here
}

// your code makes call like this
whatever( &yourArray[0][0], dimOne, dimTwo );

And there''s always the STL, like vector for example, unless you have to craft your own code here for whatever reason.

If I understood your post, hope this helps

~deadlinegrunt

Advertisement
Thanx Omalacon i see my error, it has been awhile since i messed around with that stuff..but thanx

-Syntax
-dieraxx@iname.com
-Lucas
If you don''t already know the size at compile time, then I think you have to pass the array to the function as a pointer to a pointer, as in:
int** array;

Hope that helps

This topic is closed to new replies.

Advertisement