I am trying to return an array of integers from a method into an array in my main. I know that you cannot pass an array in C, but you can pass a pointer to the array. My problem is though that every time I pass the pointer, I seem to get random numbers that are unrelated to the actual array back when magicsquaresize is less than/equal to 9. When it is less than 16, part of the array back is the actual array in main and when magicsquare is 25 or more, the whole array is actually brought back. I am really confused on why this would be. Here is my code:

//in my main 
    int* mptr = initSquare (magicsquaresize ) ;

    printf("\n");
    int i;
    for (i = 0; i<magicsquaresize;i++) {
        printf( "mptr[%d] = %d\n",i, *mptr);


    //int initSquare, magicsquare is an array of ints that is def correct:
    int *mptr = magicsquare;
    for (i = 0; i<magicsquaresize;i++) {
        printf( "mptr[%d] = %d\n",i,*(mptr+i));    
    }
    return mptr;

Thz for any help anyone can give me.

I would suspect you don't have space allocated for the array. How big is the array you defined? Or have you defined just a pointer?

Can't tell from what you've posted.

I am just trying to get the pointers to work so I completely altered my code but it is still not working. I was thinking I didn't allocate enough space, but when I tried that, I just got more errors, as I am not really sure how to allocate space, and malloc didn't seem to be working. My code now gets the 1st and last part of the array right, but the numbers in between still are wrong.

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


int main() {
    int *bpt = bob();
    int i;
    for (i = 0; i<9;i++) {
        printf( "bPtr[%d] = %d\n",i,*(bpt+i));    
    }
    free(bpt);
} //end of main()

int *bob() {
    int i;
    int num[9]; 
    for (i = 0; i<9; i++) {
        num[i] = i+1;
        printf("%d ",num[i]);
    }
    printf("\n");
    int *bPtr = num;
    for (i = 0; i<9;i++) {
        printf( "bPtr[%d] = %d\n",i,*(bPtr+i));    
    }
    printf("\n");
    return bPtr;

Thz for any helps guys

Well, no wonder. You're trying to return the address of a local variable, which will go out of scope as soon as the function returns. (Many compilers including gcc even issue a warning regarding this.) Try putting 'static' in front of the variable, which means that the memory allocated will remain the entire life of the program.

Thank You so much for your help. I knew it was something stupid.

This question has already been answered. Start a new discussion instead.