Ganesh Nagendran Ganesh Nagendran - 2 months ago 11
C Question

Return pointer from a function without defining the variable as static?

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

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

int *b = NULL,i;
b = func();

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 ??


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.