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

int* func();
int main(void) {

int *b = NULL,i;
b = func();
for(i=0;i<7;i++)
{
    printf("%d\n",*b);
    b++;
}
}

int * func()
{
    int *p;
     p = malloc(sizeof(int) * 7);
     int arr[]={1,2,3,4,5,6,7}; //without using static
     p = arr;
    return p;
}

How to return the address of the array to the main function for printing the values ?? Without declaring the array as static if we allocate memory for the array in heap then can we able to pass the array to the function as a pointer ??

2 Answers2

1

You are close, but not quite there.

The following expressing causes p to point to arr's address which is not the intended effect:

p = arr;

Remember, p is a pointer, and if you do not use the dereference operator *, then you are refering to the pointer's address rather than its value. arr's memory is deallocated when the function exits, and the memory malloc'd to p is lost because you reassigned the address of p to point to the address of the local variable arr.

The solution is to copy the values of arr to p using a for loop:

int i = 0;
for (; i < 7; ++i) {
  p[i] = arr[i];
}

This will print the desired result because you replaced the values of what p pointed to rather than the address of p itself.

Isaiah
  • 685
  • 2
  • 15
  • 28
0

You can't. The array is gone when you leave the function, any pointer to the array would have an undeterminate value when you leave the function, and using such a pointer in any way invokes undefined behaviour.

Your malloc () call is pointless and leads to a memory leak, because you allocate space for 7 ints on the heap, and then overwrite the pointer, so the memory can never be used or freed.

gnasher729
  • 51,477
  • 5
  • 75
  • 98
  • But when i referred for passing a variable from a function then they done it by allocating memory for it instead of making it as static. int *fun() { int *point = malloc(sizeof *point); *point=12; return point; } [link](http://stackoverflow.com/questions/7754986/returning-pointer-from-a-function) – Ganesh Nagendran Oct 30 '16 at 20:21
  • @GaneshNagendran, then you have to copy the static array elements to the recently allocated buffer, as recommended in one of the answers. – Luis Colorado Nov 01 '16 at 09:59