将地址添加到指针数组 C

Add an adress to an array of pointers C

我必须编写一个函数,在指针数组的末尾添加一个地址。这是我所做的。我想知道我做的是否正确,如果不正确,请指正。

#include <stdio.h>
#include <stdlib.h>
#define MAX 3

void add( int *array[MAX], int *addr)
{
    array = realloc(array, 1*sizeof(int));
    array[MAX+1] = addr;
}

int main()
{
    int *addr = 4;
    int *array[MAX] = {"1","2","3"};
    add(array, addr);
    int i;
    for(i = 0; i<4;i++)
        printf("%d ", array[i]);

    return 0;
}

来自 realloc 手册:

The realloc() function changes the size of the memory block pointed to by ptr to size bytes. The contents will be unchanged in the range from the start of the region up to the minimum of the old and new sizes. If the new size is larger than the old size, the added memory will not be initialized. If ptr is NULL, then the call is equivalent to malloc(size), for all values of size; if size is equal to zero, and ptr is not NULL, then the call is equivalent to free(ptr). Unless ptr is NULL, it must have been returned by an earlier call to malloc(), calloc() or realloc(). If the area pointed to was moved, a free(ptr) is done.

如果太长读不懂请解释。

首先你应该在分配内存之后使用 realloc(例如使用 malloc)而不是在本地声明之后

其次,您将指向 int ( int * ) 的指针视为我们是 int。也显示为警告

示例:

int *addr = 4; 
int *array[MAX] = {"1","2","3"}; 
array = realloc(array, 1*sizeof(int));     // here you're using sizeof( int )

另一个问题是超出数组范围

 array[MAX+1] = addr;

对于具有 3 个空格的数组 - 您有数组 [0]、数组[1] 和数组[2]。

在这一行中,您试图到达大小为 4 的数组(假定为)的数组[4] --> 越界

我建议的代码是:

代码已编辑

#include <stdio.h>
#include <stdlib.h>
#define MAX 3

void add( int **array[ MAX ], int *addr )
{
    *array = realloc( *array, ( MAX + 1 ) * sizeof( int* ) );
    (*array)[ MAX ] = addr;
}

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

    addr = &i;
    array = malloc( MAX * sizeof ( int* ) );
    for ( i = 1; i <= MAX; i++ ) {
        array[ i - 1 ] = addr + 4 * i;
    }

    add( &array, addr );

    for ( i = 0; i < MAX + 1; i++ ) {
        printf( "%p ", array[ i ] );
    }

    return 0;
}