gpt4 book ai didi

c - 将地址添加到指针数组 C

转载 作者:太空宇宙 更新时间:2023-11-04 03:36:28 25 4
gpt4 key购买 nike

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

#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;
}

关于c - 将地址添加到指针数组 C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32294463/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com