2

Here is my code:

int *myFunction()
{
    int A[3] = {1,2,3};
    return A;             //this will return the pointer to the first element in the array A
}

int main (void)
{
    int A[3];

    A = myfunction();     //A gets the return value of myFunction

    for(int j=0; j==2; j++)
    {
        B[j] = 2* A[j];   //doubles each value in the array
    }
    printf("%d",B);
    return 0;      
}

But this does not work because the A that is returned is not the actual vector. How do I get the actual vector {1,2,3} in the main function?

Shafik Yaghmour
  • 154,301
  • 39
  • 440
  • 740
Blue7
  • 1,750
  • 4
  • 31
  • 55
  • 3
    You can't do this because `A` is local to `myFunction` and it will run out of scope when `myFunction` ends, leaving `main` with an invalid pointer. (Also you didn't declare `A` in `main`.) – Kninnug Dec 05 '13 at 16:17
  • Try returning the address of A `&A` and then use it outside the method. – noMAD Dec 05 '13 at 16:20
  • Also beware that your `for` loop never runs because `j == 2` is false on the first iteration. You probably meant `j != 2`, though `j < 3` would be nicer (more common as well). – Kninnug Dec 05 '13 at 16:27

5 Answers5

2

The function myFunction allocates A, but this allocation only exists within the scope of the function. When the function returns the memory holding A is destroyed. This means that the function is returning a pointer to memory that has not been un-allocated.

The problem is that the variable A does not persist outside the function. You could use a global variable or pass a pointer to the buffer into myFunction

Global variable method:

static int A[3];

int* myFunction()
{
    A[0] = 1; A[1] = 2; //etc
    return A;
}

In this example, because A is a global, the memory pointed to by A persists throught your program's entire life time. Therefore it is safe to return a pointer to it...

As a side note, global variables should probably not be used in this way... it's a little clunky. The use of the static keyword means that A will not be accessible outside of this module (C file).

Pointer method:

void myFunction(a[3])
{
    a[0] = 1; a[1] = 2; //etc
}

int main()
{
    myA[3];
    myFunction(myA);
    // and continue to print array...
}

In this example the main() function allocates myA. This variable exists whilst the function is executing (it's an automatic variable). A pointer to the array is passed into the function, which fills the array. Therefore the main() function can get information from myFunction().

Another way to make the variable myA persist would be to allocate it on the heap. To do this you would do something like int *myA = malloc(sizeof(int) * NUMBER_OF_INTS_IN_ARRAY. This memory will then persist until you specifically desctroy it using free() or you program ends.

Jimbo
  • 4,352
  • 3
  • 27
  • 44
  • “Scope” is the wrong term; the scope of the identifier used inside the function is not a problem. The lifetime of the object is the problem. You can use an object outside of the scope of its identifier, as when its address is passed to a completely different routine. You cannot use an object after its lifetime ends. Scope is a compile-time property of identifiers. Lifetime is a run-time property of objects. E.g., the sentence “The problem is that the variable `A` does not persist outside the function.” should be “The problem is that the object `A` does not persist after function execution.” – Eric Postpischil Dec 05 '13 at 16:31
1

int A[3] = {1,2,3}; is being created on the stack, this is, it is a local array and it's memory can be used again after myFunction executes. You have to either make int A[3] static within myFunction or by placing it outside of all functions. Another option would be to create int A[3] within main and pass the address of A to myFunction so myFunction can directly modify the contents of A.

Fiddling Bits
  • 8,712
  • 3
  • 28
  • 46
0

As is, your code isn't close to working anyway... your for loop is broken, you have undefined variables in main, you have function name mismatches, and your print isn't going to do what you want anyway...

The big problem as that you've got undefined behavior going on, you can't access A[] outside of the function where it was locally defined. The easiest way to rectify that is to use dynamic memory, malloc() some memory for A in your myFunction then use the values in main and free() the memory when you're done.

Here's the example fixing your other syntax issues:

int *myFunction()
{
    int *A;
    A = malloc(3 * sizeof(int));
    A[0] = 1;
    A[1] = 2;
    A[2] = 3;
    return A;
}

int main (void)
{
    int *A = myFunction();     //A gets the return value of myFunction
    int B[3] = {0, 0, 0};
    int j;
    for(j=0; j<3; j++)
    {
        B[j] = 2* A[j];   //doubles each value in the array
    }
    free(A);
    printf("%d",B[0]);
    return 0;      
}
Mike
  • 47,263
  • 29
  • 113
  • 177
0

Pass the array to be filled as argument to the initisliser function along with its size:

size_t myFunction(int * A, size_t s)
{
  int A_tmp[3] = {1,2,3};

  size_t i = 0;
  for (; i < s && i < sizeof(A_tmp)/sizeof(A_tmp[0]); ++i)
  {
    A[i] = A_tmp[i];
  }

  return i;
}

Then call it like so:

int main()
{
  int myA[3];
  size_t s = sizeof(myA)/sizeof(myA[0]);
  size_t n = myFunction(myA, s);
  if (n < s)
    fprintf(stderr, "Caution: Only the first %zu of %zu elements of A were initialised.\n", n, s);

  // and continue to print array...
}
alk
  • 69,737
  • 10
  • 105
  • 255
0
#include <stdio.h>

int (*myFunction(void))[3]
{
    static int A[3] = {1,2,3};
    return &A;
}

int main (void){
    int (*A)[3], B[3];

    A = myFunction();

    for(int j=0; j<=2; j++)
    {
        B[j] = 2 * (*A)[j];
    }
    for(int j=0; j<3;++j)
        printf("%d ", B[j]);
    return 0;
}
BLUEPIXY
  • 39,699
  • 7
  • 33
  • 70