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

标签 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);
}

最佳答案

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

改变 do_something 中的 x 不会改变 main 函数中的 y。要么按如下方式传递对 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);
}

关于c - C 中的简单指针问题 - 错误值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5365111/

相关文章:

c++ - 传递给函数的数组参数不是常量指针吗?

c - 如何将一个节点从一个链表添加到另一个链表

c 指向字符串数组的指针数组

无法在C中创建数组

c - Atmel 工作室无法将 char 数组作为字符串发送

c - 函数中的malloc()结构,结束程序之前为free()

c++ - 使用指针时继承不起作用

c - libpcap: pcap_breakloop() 导致内存泄漏

c - -O0 处的内联函数导致 clang 中的链接失败

c - 在结构中使用什么级别的间接寻址?