Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is wrong with the following code dealing with pointers?

Tags:

c

pointers

Am I handling the pointer the wrong way? I want to update the value of a variable by passing it's address to the function.

void func(int *p){
        int x = 3;
        p = &x;
}

int main(){
        int y = 0;
        func(&y);
        printf("\n Value = %d",y);
}

I get the following output:

Value = 0 Exited: ExitFailure 11

like image 501
tryingToLearn Avatar asked Apr 15 '15 08:04

tryingToLearn


3 Answers

You must dereference the pointer to replace the value on which the pointer points.

See:

#include <stdio.h>

void func(int *p){
        int x = 3;
        *p = x;
}

int main(){
    int y = 0;
    func(&y);
    printf("\n Value = %d",y);
    return 0;
}

To remove the exit failure add the return 0; statement into the main function.

See running example: http://ideone.com/rO8Gua

like image 168
Zelldon Avatar answered Sep 24 '22 02:09

Zelldon


void func(int *p){
    *p = 3;
}

You were setting p to the address of a local variable x. First, setting the value of p doesn't change the value of y (the function just receives a copy of the address of y, and even if you change that, you are not going to change y).

Second, x is a local variable, so you cannot use it's content after the function func is terminated.

Third, you cannot change the address of y in this way because it is a local variable. You would need to declare it as a pointer.

like image 23
fede1024 Avatar answered Sep 23 '22 02:09

fede1024


You can refer to content of memory referred to by p by using *p. So, p =&x; will change p not the content of memory referred to by p. You should have used, *p = x

like image 37
nature1729 Avatar answered Sep 25 '22 02:09

nature1729