繁体   English   中英

修改双指针指向整数数组

[英]modifying double pointer to an integer array

我有一个指向int *array的指针,我对其进行了分配,然后将其传递给函数以填充数组的元素。

void function(int **arr);

int main()
{
    int *array;
    array=calloc(4, sizeof(int));
    function(&array);
    return0;
}


void function(int **arr)
{
    int *tmp;
    tmp=calloc(4, sizeof(int));
    tmp[0]=1;
    tmp[1]=2;
    tmp[2]=3;
    tmp[3]=4;
}

我想将tmp分配给arr 我该怎么做?

您不应该这样做,因为在这种情况下,因为已经为指针数组分配了内存,并且分配将覆盖存储在指针中的值,所以会发生内存泄漏。 编写功能更简单

void function(int **arr)
{
    int *tmp = *arr;

    tmp[0]=1;
    tmp[1]=2;
    tmp[2]=3;
    tmp[3]=4;
}

这是一个示范节目

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

void init( int **a, size_t n, int value )
{
    int *tmp = *a;
    size_t i = 0;

    for ( ; i < n; i++ ) tmp[i] = value++;
}

void display ( int *a, size_t n )
{
    size_t i = 0;

    for ( ; i < n; i++ ) printf( "%d ", a[i] );
    printf( "\n" );
}

int main(void)
{
    int *a;
    size_t n = 4;

    a = calloc( n, sizeof( int ) );

    init( &a, n, 0 );
    display( a, n );

    init( &a, n, 10 );
    display( a, n );

    free( a );

    return 0;
}

程序输出为

0 1 2 3 
10 11 12 13 

如果您需要在函数中重新分配原始数组,则可以通过以下方式完成

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

void init( int **a, size_t n, int value )
{
    int *tmp = *a;
    size_t i = 0;

    for ( ; i < n; i++ ) tmp[i] = value++;
}

void display ( int *a, size_t n )
{
    size_t i = 0;

    for ( ; i < n; i++ ) printf( "%d ", a[i] );
    printf( "\n" );
}


void alloc_new( int **a, size_t n )
{
    int *tmp = malloc( n * sizeof( int ) );

    if ( tmp )
    {
        free( *a );
        *a = tmp;
    }   
}

int main(void)
{
    int *a;
    size_t n = 4;

    a = calloc( n, sizeof( int ) );

    init( &a, n, 0 );
    display( a, n );

    alloc_new( &a, n );

    init( &a, n, 10 );
    display( a, n );

    free( a );

    return 0;
}

首先,您不需要在main calloc array 这是一个指针,您需要做的就是将tmp分配给它。 这是如何做:

void function(int **arr);

int main()
{
    int *array;
    size_t i;

    function(&array);
    // do stuff with array
    for (i = 0; i < 4; i++)
    {
        printf("%d\n", array[i]);
    }
    // then clean up
    free(array);

    return 0;
}


void function(int **arr)
{
    int *tmp;
    tmp=calloc(4, sizeof(int));
    tmp[0]=1;
    tmp[1]=2;
    tmp[2]=3;
    tmp[3]=4;

    *arr = tmp;
}

也许您应该在main中使用function之前先声明它。 如果编译器认为该function在应为int**参数时期望int参数,则可能会生成错误的代码...

您只是添加了声明,还是我错过了它? 如果是这样,对不起!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM