C question

trek

Senior member
Dec 13, 2000
982
0
71
how do i have a function that creates a dynamically allocated array that can be used outside the function?
 

trek

Senior member
Dec 13, 2000
982
0
71
i'm trying to do it without actually returning the array, because i want to return other information.
 

Armitage

Banned
Feb 23, 2001
8,086
0
0
What you have will work. You pass in the pointer, then allocate an array on it. You don't need to pass it back via the return value ... the argument list is fine. Just remember to free it. Putting the allocation in a seperate function can be a good way to forget to deallocate it later.
 

Ameesh

Lifer
Apr 3, 2001
23,686
1
0
i would suggest that you return the amount of memory you allocate as a return value from your function.
 

trek

Senior member
Dec 13, 2000
982
0
71
it doesn't work for me...

The test program prints garbage as it is. If you switch where the array is allocated it prints "1". The dynamic memory seems to get trashed when the function returns...
 

imported_FishTaco

Golden Member
Apr 28, 2004
1,120
0
0
trek, this looks like homework so I won't give you code.

What you want is to declare the parameter of your function to take a pointer to a pointer to an int.

In the function you'll then store the pointer returned by malloc by dereferencing the pointer to a pointer to an int.

To call the function, you'll pass it the address of a pointer to an int.
 

Armitage

Banned
Feb 23, 2001
8,086
0
0
Originally posted by: FishTaco
trek, this looks like homework so I won't give you code.

What you want is to declare the parameter of your function to take a pointer to a pointer to an int.

In the function you'll then store the pointer returned by malloc by dereferencing the pointer to a pointer to an int.

To call the function, you'll pass it the address of a pointer to an int.

:eek: Whoa ... correct of course.
How embarrasing ... that's what I get for writing nothing but python & perl for the past 9 months :disgust: