指向结构的指针在传递给函数时根本不改变 [英] Pointer to structure NOT changing at all when passed to function

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

问题描述

 #define MAX_STACK 10
 typedef int STACK_ITEM;
 typedef struct Stack *STACK ;

stack.c

 #include"stack.h"

struct Stack{
    STACK_ITEM contents[MAX_STACK];
    int tos;
};

_Bool create_stack(STACK s){
    s = malloc(sizeof(struct Stack));
    if(s == NULL )
        return 0;
    s->tos = 0;
    return 1;
}

当调用 create_stack 函数时,它根本不会影响 s(指向结构的指针).所以,我的问题是:为什么 s 改变,即使它是一个指针,而不是一个值,传递?

When calling the create_stack function, it doesn't affect s (pointer to structure) at all. So, my question is: why is s not changing, even though it is a pointer, not a value, passed?

推荐答案

记住,所有参数在C语言中都是按值传递的.

Remember, all parameters are passed by value in C.

当您将指针作为函数参数传递时,您可以访问该指针所指向的对象(或对象数组).

When you pass a pointer as a function parameter, you can access the object (or array of objects) pointed to by that pointer.

您的create_stack() 被传递一个指向struct Stack 的指针,即s 参数.然后它忽略 s 的原始值并重新分配它.这是允许的,但请注意它不会更改 create_stack() 调用者中的原始指针,因为函数参数是按值传递的.

Your create_stack() is passed a pointer to a struct Stack, that is the s parameter. It then ignores the original value of s and reassigns it. That is allowed, but note that it does not change the original pointer in the caller of create_stack() because function parameters are passed by value.

有两种方法可以做你想做的事.

There are two ways to do what you want.

第一种方式是将指针传递给指针:

The first way is to pass a pointer to a pointer:

_Bool create_stack(STACK *s){
    *s = malloc(sizeof(struct Stack));
    if(*s == NULL )
        return 0;
    (*s)->tos = 0;
    return 1;
}

称它为例如:

STACK mystack;
_Bool ret;

ret = create_stack(&mystack);
if (!ret) {
    /* error */
}

第二种方式是不传递任何东西,返回一个指向已分配堆栈的指针:

The second way is to not pass anything and return a pointer to the allocated stack:

STACK create_stack(void){
    STACK s = malloc(sizeof(struct Stack));
    if(s != NULL ) {
        s->tos = 0;
    }
    return s;
}

称它为例如:

STACK s;

s = create_stack();
if (s == NULL) {
    /* error */
}

最后,作为编程风格的一点,不要像你所做的那样typedef指针.如果指针是显式的,则更清楚,例如,使用 typedef struct Stack STACK; 而不是 typedef struct Stack *STACK; 并相应调整用法,例如,替换STACK s 替换为 STACK *s 并将 STACK *s 替换为 STACK **s.

Finally, as a point of programming style, do not typedef pointers in the way you have done. It is clearer if the pointer is explicit, for example, use typedef struct Stack STACK; instead of typedef struct Stack *STACK; and adjust the usage accordingly, for example, replacing STACK s with STACK *s and replacing STACK *s with STACK **s.

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

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