Quote:
> Hi
> I have a large array of unsigned long and I want to populate the array
> within a function. Rather than passing the entire array into the
> function, I want to just pass a pointer to the array into the
> function, and then be able to load the data into the array from there.
> int main(int argc, char *argv[]){
> unsigned long address;
> unsigned long wordcount;
> unsigned long memory[MEMORY_SIZE], *p;
> p = &memory[0];
> .
> .
> .
> loader(*p);
> }
> void loader(unsigned long *p){
> //Load data into array
> ???
> }
> I am not sure if I've setup the pointer correctly.
Not quite. Instead of loader(*p), it's just loader(p), or indeed
loader(memory) - yes, you did more work than you needed to! You see,
when you try to pass an array to a function, the compiler says "yeh,
right" and converts it to a pointer to the first element of that array.
To actually pass the whole array by value (not a good plan), you'd have
to do a bit of extra work which I won't go into now.
Quote:
> Also once in the
> function how do I access the different array elements???
p[i] = 42;
where i is the element you want (in your case, i must have a value
between 0 and (MEMORY_SIZE - 1).
Note: it would be a good idea to send loader() the size of the array
too, as this reduces the coupling between main() and loader(). Also,
give loader() a prototype.
Something like this:
void loader(unsigned long *p, size_t count);
int main(int argc, char *argv[])
{
unsigned long address;
unsigned long wordcount;
unsigned long memory[MEMORY_SIZE] = {0}; /* initialises first element
to 0, and everything else to the default (which, for unsigned long, is
0). */
.
.
.
loader(memory, MEMORY_SIZE);
/* or even this: */
loader(memory, sizeof memory / sizeof memory[0]);
/* main returns int, so let's return an int */
return 0;
Quote:
}
void loader(unsigned long *p, size_t count)
{
/* Load data into array */
Valid values are p[0] through p[count - 1].
Quote:
}
HTH. HAND.
--
"Usenet is a strange place." - Dennis M Ritchie, 29 July 1999.
C FAQ: http://www.eskimo.com/~scs/C-faq/top.html
K&R answers, C books, etc: http://users.powernet.co.uk/eton