Pointer to 2D array changes address when I print it

I can't seem to understand why is my pointer changing address in this situation :

int *load(FILE *fp, int * vector, int w, int h){
    //other coding
    int array[w][h];
    int *ptr = &array;
    return ptr;
}

main(){
    //other coding
    int *ptr = load(file, vector, w, h);
    printf("%d ", *(ptr));
    printf("%d ", *(ptr));
}

In my first printf("%p ", *(ptr)); it prints 00000010

In my second printf("%p ", *(ptr)); it prints 0028fc6c

And for sure if I print the values with "%d" first one is good, second one is not.

Upvotes: 0

Views: 182

Answers (4)

UserM
UserM

Reputation: 320

You are trying to print address of array declared locally. Declare the array outside the function i.e globally.

Try this method:

int array[w][h];


int *load(FILE *fp, int * vector, int w, int h){
    //other coding
    int *ptr = &array;
    return ptr;
}

main(){
    //other coding
    int *ptr = load(file, vector, w, h);
    printf("%d ", *(ptr));    
}

Upvotes: 0

AnT stands with Russia
AnT stands with Russia

Reputation: 320709

Firstly, you are not printing a pointer, you are printing the value pointed by the pointer. This is what the unary * operator does: it gives you access to the pointed value. So nothing you observed implies in any way that some "address" has changed. You are not inspecting any addresses in your program.

Secondly, the above likely means that it is not the pointer that changes. It is the pointed value that changes. And indeed, the pointer you returned from function is referring to an invalid memory location (the site of former local array that no longer exists). There's nothing unusual in the fact that an invalid memory location changes it values without any apparent reason. It is called undefined behavior. Your program could have crashed, but out of pure luck instead of a crash you got a value that changes "inexplicably".

Thirdly, even if your code might get "compiled" by a lenient compiler, it still contains constraint violations, i.e. "compile errors". This initialization is invalid

int *ptr = &array;

The &array value has type int (*)[w][h]. It cannot be used to initialize a pointer of type int *. I'm sure the compiler told you about it. You have to pay closer attention to the diagnostic messages issued by your compiler.

Upvotes: 0

Eshant Sahu
Eshant Sahu

Reputation: 360

When you are printing the *(ptr) it is trying to print the value at location ptr , if you want to print the address of ptr try &(ptr).

Upvotes: 0

Rohan
Rohan

Reputation: 53386

The array address you are returning from load() is local variable of that function. You should never return its address, as its allocated on stack and will be reused for subsequent function calls.

The changed values you are seeing are because call to printf()s are updating that location of stack.

Upvotes: 1

Related Questions