将结构指针传递给c中的函数 [英] Passing struct pointer to function in c

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

问题描述

我在将指向结构的指针传递给函数时遇到问题.我的代码基本上如下所示.在主函数中调用 modify_item 后,stuff == NULL.我希望 stuff 是指向元素等于 5 的项结构的指针.我做错了什么?

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.

要么传递一个指向指针的指针(即struct item **),要么让函数返回指针.

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

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

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