-3
#include <stdio.h>

int* createReverseArray(int *array, int size)
{
    int i;
    int newArray[size];
    for(i=size-1; i>=0; i--)
    {
        newArray[i] = array[size-i-1];
    }

    return newArray;
}

int main(void) {

    int myArray[] = {1,2,3,5,1};
    int myArray2[] = {1,2,3,4,2,1};
    int i;

    int size = sizeof(myArray)/sizeof(int);
    printf("Size: %d\n", size);
    int* newArray = createReverseArray(myArray, size);

    for(i=0; i<size; i++)
    {
        printf("%d, ", newArray[i]);
    }

    return 0;
}

I printed the array within the createReverseArray function and got the correct output, but when I return the pointer to the array and then try to print the results, I think it's printing pointers to each array spot? I'm not quite sure.

This returns:

Size: 5

12341002, 1, -10772231820, -1077231812, 1074400845,

DJSweetness
  • 153
  • 1
  • 14
  • 2
    This is a classic error that I'm pretty sure has been asked about before on StackOverflow. You are returning a pointer to memory allocated inside a function, and that function will go away. The Go language is smart enough to make this work and move that memory to the heap, but C cannot do this. You have to malloc space for this array yourself. – Ray Toal Feb 26 '17 at 19:36
  • 1
    @RayToal: It has been asked just 1000+ times ... And yes, it is a very basic error which results from not starting with the fundamental concepts of the language. Like one gets from a good C book. – too honest for this site Feb 26 '17 at 19:55

1 Answers1

2

newarray is an automatic local variable. It will no longer exists once function return. Returning pointer to an automatic local variable invoke undefined behaviour and in this case nothing good can be expected.

You can allocate memory diynamically and then return pointer to it

int *newArray = malloc(sizeof(int)*size); 
haccks
  • 104,019
  • 25
  • 176
  • 264