C中的简单指针问题 - 错误的值

时间:2011-03-19 21:46:34

标签: c pointers

我正在做一些简单的事情,使用链接列表,我意识到有一些我不理解的东西。我无法弄清楚为什么下面的程序不打印3(它打印一个随机数)。我认为在运行时没有错误并且y不是NULL也很奇怪。

struct ceva
{
    int y;
};

typedef struct ceva str;

void do_something(str *x)
{
    str *p = (str *)malloc (sizeof (str));
    p->y = 3;
    x = p;
}

int main(void)
{
    str *y;
    do_something (y);
    printf ("%d", y->y);
}

6 个答案:

答案 0 :(得分:4)

您将str x的值传递给函数do_something

x中更改do_something不会更改y功能中的main。要么将引用传递给y,如下所示:

void do_something(str **x)
{
    str *p = (str *)malloc (sizeof (str));
    p->y = 3;
    *x = p;
}

int main(void)
{
    str *y;
    do_something (&y);
    printf ("%d", y->y);
}

或使函数do_something返回它分配的结构的地址:

以下是在C中执行此操作的常用方法。

str *do_something(void)
{
    str *p = (str *)malloc (sizeof (str));
    if (p)  // ensure valid pointer from malloc.
    {
        p->y = 3;
    }
    return p;
}

int main(void)
{
    str *y = do_something (y);
    printf ("%d", y->y);
}

答案 1 :(得分:2)

这是你想要做的:

void do_something(str **x)
{
    str *p = (str *)malloc (sizeof (str));
    p->y = 3;
    *x = p;
}

int main(void)
{
    str *y;
    do_something (&y);
    printf ("%d", y->y);
}

否则传递指针的副本将设置为您想要的值

答案 2 :(得分:1)

为了改变y,你需要发送& y,所以do_something参数实际上需要是str ** x

struct ceva{
int y; 
};
typedef struct ceva str;
void do_something(str **x)
{
str *p = (str *)malloc (sizeof (str));
p->y = 3;
*x = p;
}
int main(void)
{
str *y;
do_something (&y);
printf ("%d", y->y);
}

答案 3 :(得分:1)

由于C 按值传递y会保留回指向某些垃圾,其状态位于main()。要实际执行您的预期,do_something(..)应返回str *类型的引用。

str* do_something(str *x)
{
    str *p = (str *)malloc (sizeof (str));
    p->y = 3;
    x = p;
    return x ;
}

//需要收集返回的值。

str *y;  // It's a good practice to set y to NULL. Do this instead. str *y = NULL ;
y = do_something (y);

答案 4 :(得分:1)

x = p;将已分配内存的位置分配给 本地 变量x,这会立即被遗忘。返回已分配结构的地址,如:

str* do_something() {
    str *p = (str *)malloc (sizeof (str));
    p->y = 3;
    return p;
}
int main() {
    str * y = do_something();
    printf("%d", y->y);
}

或者提供地址do_something可以将地址[原文如此]写入:

void do_something(str** x) {
    str *p = (str *)malloc (sizeof (str));
    p->y = 3;
    *x = p;
}
int main() {
    str* y;
    do_something(&y);
    printf("%d", y->y);
}

答案 5 :(得分:0)

试试下面的程序。你的程序需要一些修正。

struct ceva
{
    int y;
};

typedef struct ceva str;

ceva* do_something()
{
    str *p = (str *)malloc (sizeof (str));
    p->y = 3;
    return p;
}

int main(void)
{
    str *y = (str *)malloc (sizeof (str));;
    y->y = 2;
    y = do_something ();
    printf ("%d", y->y);
}