传递结构函数指针在C [英] Passing struct pointer to function in c

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

问题描述

我在与一个指针传递给一个结构到功能的问题。我的code是什么本质如下所示。在主函数中调用modify_item后,东西== NULL。我想要的东西是指向某个项目结构与元素等于5。我在做什么错了?

 无效modify_item(结构项目* S){
   结构项目* retVal的malloc的=(的sizeof(结构件));
   retVal->元素= 5;
   S = retVal的;
}诠释主(){
   结构项目*的东西= NULL;
   modify_item(东西); //这个调用,东西== NULL之后,为什么呢?
}


解决方案

由于您是按值传递的指针 。功能上的指针的一个拷贝操作,并且从未修改原始

无论是传递一个指针的指针(即一个结构件** ),或代替具有函数返回的指针。

I'm having a problem with passing a pointer to a struct to a function. My code is essentially what is shown below. After calling modify_item in the main function, stuff == NULL. I want stuff to be a pointer to an item struct with element equal to 5. What am I doing wrong?

void modify_item(struct item *s){
   struct item *retVal = malloc(sizeof(struct item));
   retVal->element = 5;
   s = retVal;
}

int main(){
   struct item *stuff = NULL;
   modify_item(stuff); //After this call, stuff == NULL, why?
}

解决方案

Because you are passing the pointer by value. The function operates on a copy of the pointer, and never modifies the original.

Either pass a pointer to the pointer (i.e. a struct item **), or instead have the function return the pointer.

这篇关于传递结构函数指针在C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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