我想try 为列表中的单元格创建一个allocate函数,但是当在其他函数中使用它时,我需要添加一个""号

我知道""在c中的意思(变量的地址),但我不明白为什么我需要在这里使用它?

这是我创建的分配函数

/*1*/void Allocate(struct cell **p) {
  (*p) = malloc(sizeof(struct cell));
}

这就是我使用它的函数

void Makelist(struct cell **headP, int n){
    struct cell *q;
    struct cell *p;
    int value;
    Allocate(&p);///whyyyy????
    *headP=p;
    Ass_adr(p,NULL);
    printf("\ngive the value on cell 1:");
    scanf("%d",&value);
    Ass_val(p,value);
        for (int i=1; i<n;i++){
            Allocate(&q);
            Ass_adr(q,NULL);
            Ass_adr(p,q);
            printf("give the value in the cell %d:",i+1);
            scanf("%d",&value);
            Ass_val(p,value);
            p=q;
        }
}

我以为我只会打字

Allocate(p);

然而,如果我没有在主程序中添加"",它就会正常运行

推荐答案

在C中,通过引用传递意味着通过指向对象的指针间接传递对象.因此,取消引用传递的指针后,您可以直接访问原始对象,并可以对其进行更改.

C标准(6.2.5类型,第20页)中写道:

-A pointer type may be derived from a function type or an object type, called the referenced type. A pointer type describes an object whose value provides a reference to an entity of the referenced type.从引用类型T派生的指针类型有时 称为"指向T的指针".

因此,要更改函数中的原始对象(该对象可以是指针),您需要传递对它的引用,即指针.

在此代码片段中

struct cell *p;
//...
Allocate(&p);

指针p被传递给通过引用分配的函数.因此,该函数改变了原始传递的对象(指针)p

(*p) = malloc(sizeof(struct cell));

否则,如果要直接传递指针,则它将通过值传递给函数.也就是说,该函数将处理原始指针的副本,并且该副本将被更改.原始指针将保持不变.

考虑以下简单的解除保险计划:

#include <stdio.h>

void f( int *p )
{
    p = NULL;
}

void g( int **p )
{
    *p = NULL;
}

int main( void )
{
    int x = 10;

    int *p = &x;

    printf( "Before calling function f() p = % p\n", ( void * )p );

    f( p );

    printf( "After  calling function f() p = % p\n", ( void * )p );

    printf( "Before calling function g() p = % p\n", ( void * )p );

    g( &p );

    printf( "After  calling function g() p = % p\n", ( void * )p );
}

程序输出可能如下所示

Before calling function f() p = 00CFF9FC
After  calling function f() p = 00CFF9FC
Before calling function g() p = 00CFF9FC
After  calling function g() p = 00000000

C++相关问答推荐

C中空终止符后面的数字?

在函数中使用复合文字来初始化C语言中的变量

C:二进制搜索和二进制插入

为什么在函数内部分配内存空间时需要添加符号?

如何在C宏中确定 struct 中元素的类型?

struct 上的OpenMP缩减

调用mProtection将堆栈上的内存设置为只读,直接导致程序SIGSEGV

Setenv在c编程中的用法?

我在C程序的Flex/Bison中遇到语法错误

Fprintf正在写入多个 struct 成员,并且数据过剩

C-try 将整数和 struct 数组存储到二进制文件中

使用正则表达式获取字符串中标记的开始和结束

CS50 pset 5的皱眉脸正确地处理了大多数基本单词,并且拼写判断不区分大小写.

I';我试着从.txt文件中读取文本,并用c计算其中的单词数量

在哪里可以找到叮当返回码的含义?

为什么程序在打印每个数字之前要等待所有输入?

SSE 向量与 Epsilon 的比较

C 预处理器中的标记分隔符列表

如何确保 gcc + libc 对于多字节字符串使用 UTF-8,对于 wchar_t 使用 UTF-32?

如何在C中以0x格式打印十六进制值