please anyone help me to catch this.i tried to return an array from function and access it within main function.i just got a warning

"function returns address of local variable
 "

and when i execute the program it gives garbage values as array elements..cam you help me pls...

#include<stdio.h>

int *foo(void);

int main()
{
int i;  
int *ptr=foo();


for(i=0;i<4;i++)
printf("%d	",*(ptr+i));

return 0;
}


int *foo()
{

int ar[4]={1,2,3,4};



return ar;
}

You have to create your array on the heap in this situation...Returning an address to an array on the stack won't work because the address is invalid as soon as the function returns..

You have to create your array on the heap in this situation...Returning an address to an array on the stack won't work because the address is invalid as soon as the function returns..

thamks for your quick reply.but i don't fully understand your explanation..can you explain it in another way..thanx

You have to create your array on the heap in this situation...Returning an address to an array on the stack won't work because the address is invalid as soon as the function returns..

thanks for your quick reply.but i don't fully understand your explanation..can you explain it in another way..thanks

Because a returning function will invalidate all its variables, you can't return the address to any of them and expect consistent results...Here's one way to solve your problem using the heap.

#include <stdio.h>
#include <stdlib.h>

#define ARR_SIZE 4

int* foo(void);

int main()
{
	int i = 0;
	int *ans = foo();

	for (; i < ARR_SIZE; ++i)
		fprintf(stdout, "ans->%d\n", ans[i]);

	free(ans);
	return 0;
}

int* foo(void)
{
	int i = 0;
	int *ar = (int*)malloc(ARR_SIZE * sizeof(int));
	
	for (; i < ARR_SIZE; ++i)
		ar[i] = i + 10;

	return ar;
}

Edited 6 Years Ago by gerard4143: n/a

Because a returning function will invalidate all its variables, you can't return the address to any of them and expect consistent results...Here's one way to solve your problem using the heap.

#include <stdio.h>
#include <stdlib.h>

#define ARR_SIZE 4

int* foo(void);

int main()
{
	int i = 0;
	int *ans = foo();

	for (; i < ARR_SIZE; ++i)
		fprintf(stdout, "ans->%d\n", ans[i]);

	free(ans);
	return 0;
}

int* foo(void)
{
	int i = 0;
	int *ar = (int*)malloc(ARR_SIZE * sizeof(int));
	
	for (; i < ARR_SIZE; ++i)
		ar[i] = i + 10;

	return ar;
}

oh!thats the way...itz very helpful thanx a lot...

This question has already been answered. Start a new discussion instead.