• We’re currently investigating an issue related to the forum theme and styling that is impacting page layout and visual formatting. The problem has been identified, and we are actively working on a resolution. There is no impact to user data or functionality, this is strictly a front-end display issue. We’ll post an update once the fix has been deployed. Thanks for your patience while we get this sorted.

C question

trek

Senior member
how do i have a function that creates a dynamically allocated array that can be used outside the function?
 
i'm trying to do it without actually returning the array, because i want to return other information.
 
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.
 
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...
 
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.
 
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.

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