问题更改C空指针值 [英] Problems changing a void pointer value in C

查看:156
本文介绍了问题更改C空指针值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上我的问题是,我试图修改英勇变量中的值,从而调用 cambiar_valor 函数它chenges 25。但我的问题是,它不昌的。我究竟做错了什么?我试图做一个真正的通用功能,以便根据不同的数据类型,我传递给函数它dinamically变化。在这种情况下是一个整数类型,但我想在这里做的是检查,如果我可以改变函数内部的英勇变量的值

 #包括LT&;&stdio.h中GT;
#包括LT&;&stdlib.h中GT;无效cambiar_valor(void *的勇气,为int * valor_dos){//分配valor_dos以勇武
    英勇= valor_dos;
}诠释主(){
    void *的勇气;
    为int * valor_dos = 25;
    cambiar_valor(勇武,valor_dos);
    的printf(%d个\\ N,为(int *)勇武); //这应该显示25
    返回0;
}


解决方案

在你的函数

 无效cambiar_valor(void *的勇气,为int * valor_dos){//分配valor_dos以勇武
    英勇= valor_dos;
}

您传递指针按价值计算,这意味着英勇 valor_dos 你传递参数的副本英寸重新分配英勇里面的函数的调用函数没有影响。

要解决这个问题,采取的参数通过指针:

 无效cambiar_valor(无效**的勇气,为int * valor_dos){//分配valor_dos以勇武
    *勇气= valor_dos;
}

然后调用

  cambiar_valor(安培;勇武,valor_dos);

此外,作为@Levon提到,你的 valor_dos 初始化的不正确,可能会导致段错误在运行时。你可能想改变这一点。

希望这有助于!

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;
}

解决方案

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!

这篇关于问题更改C空指针值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆