-
February 23rd, 2009, 05:31 PM
#1
passing pointers of array to function
Hello everyone,
ive been googleing this all day and havent found an answer yet.
i want to create an array in int Main() and then pass a pointer referencing the
array to a function to fill it.
This is how far i have gotten:
Code:
int main(void)
{
test();
float dat[1000];
readnprint(&dat[0]);
/*
other code her
*/
}
void readnprint(float *base_ptr)
{
//init ifstream etc etc..
float addr=base_ptr;
while (!ins.eof())
{
ins>>x;
float f;
if(from_string<float>(f, string(x), dec)) //parse float?
{
addr=(base_ptr)+(sizeof(float)*cnt) //steps through array by sizeof(float)
*(float)addr=f; //have this assign the value to memory location (problem)
}
else
{
cout << "from_string failed" << endl;
}
cnt++;
}
ins.close();
}
im sure im just tired and not thinking right, does anyone have a better/working way of doing this?
thanks
-maze
-
February 23rd, 2009, 05:44 PM
#2
Re: passing pointers of array to function
Originally Posted by madmaze
im sure im just tired and not thinking right, does anyone have a better/working way of doing this?
Why are you working with arrays? A proper container (e.g., std::vector) is more robust and safer.
As for the other part of your problem, this is easily solvable with std::generate and a functor.
-
February 24th, 2009, 12:09 AM
#3
Re: passing pointers of array to function
This is one way of doing it.
Code:
void main()
{
float dat[1000];
readnprint(dat, 1000);
}
void readnprint(float* base_ptr, int size)
{
for (int i = 0; i < size; ++i)
{
base_ptr[i] = i;
}
}
-
February 24th, 2009, 02:11 AM
#4
Re: passing pointers of array to function
Originally Posted by _Superman_
This is one way of doing it.
Note that void main() should be int main(), as in madmaze's original example.
-
February 24th, 2009, 01:36 PM
#5
Re: passing pointers of array to function
not sure what i was thinking last night.. simply passing by ref is the easiest..
thanks for the responses =)
Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|