Passing an array address from a function.

Can anyone help me in printing the array of the function getIt() in the main().
The program is--


#include<stdio.h>
#define MAX 50

int* getIt()
{
int i,a[]={
1,2,3,4,5,6
};
printf("The address of the numbers sequentially are-\n");
for(i=0;i<6;i++)
printf("%x\n",a+i);
return a;
}
int main()
{
int i;
int*b;
b=getIt();
printf("The return address-%x\n",b);
for(i=0;i<6;i++)
printf("%d ",*(b+i));
printf("\n");
return 0;
}

The program output is--

The address of the numbers sequentially are-
22fee0
22fee4
22fee8
22feec
22fef0
22fef4
The return address-22fee0
1 1977289080 1976768654 -1734955464 0 0

The array you create is a local variable in the function getIt. When a function ends, local variables cease to exist. The memory that held them is available for the program to write over with anything it likes. You are thus returning a pointer to some place in memory that the program can (and will) write all over whenever it likes.

The function

int* getIt()
{
int i,a[]={
1,2,3,4,5,6
};
printf("The address of the numbers sequentially are-\n");
for(i=0;i<6;i++)
printf("%x\n",a+i);
return a;
}

is defined incorrectly. Array a is a local to the function and will be deleted after exiting it. So you shall declare it as a static array.

1
2
3
4
5
6
7
8
9
int* getIt()
{
   static int a[]={ 1, 2, 3, 4, 5, 6 };

   printf("The address of the numbers sequentially are-\n");
   for( int i=0; i<6; i++ ) printf( "%x\n", a+i );

   return a;
}
Thanks! It's fine now.
Topic archived. No new replies allowed.