问题
Basically my problem is that i'm trying to change the value inside the valor
variable, so that after calling of the cambiar_valor
function it chenges to 25. But my problem is that it doesn't chang at all. What am i doing wrong here?. I'm trying to make a really generic function so that depending of the data type i pass to the function it changes dinamically. In this case is an integer type but what i'm trying to do here is to check if i could change the value of the valor
variable inside the function
#include<stdio.h>
#include<stdlib.h>
void cambiar_valor(void* valor,int* valor_dos) {//assign valor_dos to valor
valor = valor_dos;
}
int main() {
void *valor;
int *valor_dos = 25;
cambiar_valor(valor,valor_dos);
printf("%d \n",(int*)valor);//this should show 25
return 0;
}
回答1:
In your function
void cambiar_valor(void* valor,int* valor_dos) {//assign valor_dos to valor
valor = valor_dos;
}
You are passing in the pointers by value, meaning that valor
and valor_dos
are copies of the parameters you pass in. Reassigning valor
inside the function has no effect on the calling function.
To fix this, take the parameters in by pointer:
void cambiar_valor(void** valor, int* valor_dos) {//assign valor_dos to valor
*valor = valor_dos;
}
Then call
cambiar_valor(&valor, valor_dos);
Also, as @Levon has mentioned, your initialization of valor_dos
in main
is incorrect and will probably cause a segfault at runtime. You might want to change that as well.
Hope this helps!
回答2:
Here
int *valor_dos = 25;
you are initializing a pointer to an int with the value 25 .. I.e.,it points at memory location 25, that can only lead to trouble. I'm surprised you didn't get a seg fault.
回答3:
int *valor_dos = 25
This statement is incorrect. You are declaring a pointer here, so you cannot assign a value (25) to it.
来源:https://stackoverflow.com/questions/11044555/problems-changing-a-void-pointer-value-in-c