strawberry731
strawberry731

Reputation: 15

Integer double pointer in function parameter

What I've learned so far about pointers is: a pointer refers to the address of a variable

int a = 0 ;
int *p = &a ;

and a double pointer refers to the address of a pointer variable

int *b = &a ;
int **c = &b ;

and as far as what I know is correct, I should have no problem in executing the codes below:

#include<stdio.h>

void reference(int **input)
{
    **input = 963;
}

int main(void)
{
    int* value;

    reference(&value);

    printf("%d\n", *value);

    system("PAUSE");
    return 0;
}

In this code, I expected to see "963" in console. When I execute the code, build succeeds but cmd just stops. What could be a possible problem for this simple code?

Upvotes: 0

Views: 44

Answers (2)

melpomene
melpomene

Reputation: 85767

We can rewrite

int* value;
reference(&value);

without the function, giving

int* value;
int **input = &value;
**input = 963;

Because *input is value, the whole thing is equivalent to

int* value;
*value = 963;

This is wrong because value is uninitialized. Dereferencing an uninitialized pointer has undefined behavior.

Fix:

int x;
int *value = &x;
reference(&value);

I.e. make value point somewhere were 963 can be stored.

Upvotes: 4

Matthieu Brucher
Matthieu Brucher

Reputation: 22023

The issue is that value is a pointer that doesn't point to anything, it's dangling. You need to set it first.

int foo;
int* value;
value = &foo;

And now it works without crashing. You need to have a place for your data, either ont he stack (local variables) or on the heap (allocated with malloc).

Upvotes: 2

Related Questions