
Returning Int array pointers from functions
[ snip ]
Quote:
> Now onto the code:
> prototypes & variable declarations:
> int *Day_Convert(char *Info)
> int Deadline[2], *Ptr_2_Deadline;
> Ptr_2_Deadline=Deadline;
> Ptr_2_Deadline=Day_Convert(char *The_Date_String)
Uhhh! this last affectation overrides the previous one. As declared, the
function Day_Convert returns a pointer to int, so the question is :
"Does the value returned point to dynamically allocated memory, or does
it point to some static data ?". In your 2 above statements, you seem to
mix the two points.
Quote:
> /* This doesn't work nor does using a pointer below */
> printf("(%d, %d) (month, day)\n", Deadline[0],Deadline[1]);
> /* Output tends to be (0,0) (month, day) and inspection shows a unmodified
> array of (0,0) */
> int *Day_Convert(char *Info)
> {
> int When[2], *Ptr_2_When, Index=0;
> char Month_Array[3], Day_Array[3];
> Ptr_2_When=When;
> /** Read in month and then read in day **/
> /** Data is from a WWW form, so is predictable **/
> for(Index=0;Index<2;Index++)
> {
> Month_Array[Index]=*Info;
> Info++;
> /** BTW Can I safely say Month_Array[Index]=*Info++ ???? */
Yes, no problem.
Quote:
> }
> Info++;
> for(Index=0;Index<2;Index++)
> {
> Day_Array[Index]=*Info;
> Info++;
> }
> When[0]=atoi(Month_Array);
> When[1]=atoi(Day_Array);
> /* When inspecting during debugging sessions, everything works till here */
> /* I.e. When[0]=8 and When[1]=31 which are correct for the data given */
> return When;
> }
The problem is here : "When" is an automatic variable, it is allocated
on the stack and its life duration is the scope of the function
Day_Convert. The returned value has no meaning outside the function and
invokes undefined behaviour. If you choose to return a pointer to
dynamically allocated data, you have to change the declaration of the
variable "When", use (m)alloc, and through Ptr_2_When :
int *When;
When = malloc(2 * sizeof *When);
Quote:
> I've also tried a slightly different approach by using the target for the
> return as an argument to the function (i.e. void Day_Convert(char *Info, int
> *Day_of_Deadline); and I get the same results it doesn't seem to work.
This is an usual approach and I think it is better in your case, because
it avoids dynamic memory allocation. From this point of view, it is not
to the callee to do the memory allocation, but this is left to the
caller. It can be used when the size of the data is either known at
compile time, or is limited to an (reasonable) upper bound.
Such a function should work :
void Day_Convert(char *Info, int *Day_of_Deadline)
using Deadline instead of When in the function body
Day_Convert(The_Date_String, Deadline);
--
Herve Couppe de Lahongrais (SEU) | Eurocontrol Experimental Centre