如何将指向动态分配数组的指针作为函数参数传输

How to transmit pointer to dynamically allocated array as a function parameter

我想在函数内部分配一个数组,并能够在函数外部使用指向该数组的指针。我不知道我的代码有什么问题

#include <stdio.h>
#include <stdlib.h>

void alloc_array (int **v, int n)
{
    *v=(int *)calloc(n,sizeof(int));
    printf ("the address of the array is %p",v);
}

void display_pointer (int *v)
{
    printf ("\n%p",v);
}

int main()
{
    int *v;
    alloc_array(&v,3);
    display_pointer(v);

    return 0;
}

我希望在两个 printf 中获得相同的地址,但事实并非如此。我的错误是什么?

void alloc_array (int **v, int n)
{
    *v = calloc(n,sizeof(int));
    printf("the address of the array is %p", *v);
    //                                   ----^
}

请注意我的 printf 通话中的额外星星。

此外,不要转换 malloc / calloc 的 return 值。

v in alloc_array 包含指针变量的地址。该变量是 vin main().

你不关心它。因为它不会改变。但是 mainv 的内容会。

你应该打印 *v 但为什么呢?

因为valloc_array中的内容包含了你分配的内存地址。

但是display_pointer不需要这个。因为在这里你传递了指针变量本身,它在 called 函数中的本地副本将包含你分配的内存地址。

在此代码段中

int *v;
alloc_array(&v,3);
display_pointer(v);

函数alloc_array接受变量(指针)的地址v并在函数中输出这个地址

printf ("the address of the array is %p",v);

另一方面,函数 display_pointer 接受存储在变量 v 中的值,并且该值在函数

中输出
printf ("\n%p",v);

在函数中多加一条语句alloc_array,你就会看到区别

printf ("the address of the original pointer is %p", ( void * )v);
printf ("the address of the first element of the allocated array is %p", ( void * )*v);