使用具有动态数组的结构指针的内存分配(realloc)时出错

Але*_*Рак 2 c memory-management function std

vector_int.h是一个带有自制动态数组(向量)结构的头.

test.c是一个测试程序.

所有代码如下:

vector_int.h:

#include <stdio.h>

typedef struct 
{
    long int len; // Length
    int *array;   // Dynamic Array
} IntVector; 

void ResizeIntVector(IntVector *vector, int size) // Resizing of vector
{
    realloc(vector->array, size * sizeof(int));
    vector->len = size; // Changing of length variable
}

void SetIntVectorCell(IntVector *vector, unsigned int cell_number, int cell_value) // Put cell_value in array[cell_number]
{
    if (cell_number >= vector->len)
        ResizeVectorInt(&vector, cell_number); // Grow size of memory if it's not enough

    vector->array[cell_number] = cell_value;
}
Run Code Online (Sandbox Code Playgroud)

test.c的:

#include "vector_int.h"
#include <stdio.h>

int main()
{
    IntVector vector;

    int n;
    scanf("%d", &n);

    int i;
    for (i = 0; i < n; i++) // testing
    {
        SetIntVectorCell(&vector, i, i);
        printf("%d ", vector.array[i]);
    }

    return 0;       
}
Run Code Online (Sandbox Code Playgroud)

日志:

1   0   D:\Work\Raspberry Pi\test.c In file included from D:\Work\Raspberry Pi\test.c
        D:\Work\Raspberry Pi\vector_int.h   In function 'ResizeIntVector':
11  2   D:\Work\Raspberry Pi\vector_int.h   [Warning] incompatible implicit declaration of built-in function 'realloc' [enabled by default]
            [Linker error] C:\Users\ALEXAN~1\AppData\Local\Temp\cccFKqxs.o:test.c:(.text+0x4a): undefined reference to `ResizeVectorInt'
            collect2: ld returned 1 exit status
Run Code Online (Sandbox Code Playgroud)

我认为使用realloc函数存在错误,但我认为我做得很好.请帮助我,找出错误或错误.

pb2*_*b2q 9

你有一些问题:

  • implicit declaration/realloc问题是因为你需要包含stdlib.hrealloc签名.如果没有函数签名,编译器会对函数参数和返回值做出一些假设,然后在链接期间,如果这些假设与实际函数实现不匹配,链接器会抱怨这一点.

  • 您正在传递realloc尚未初始化的地址.这是在惹麻烦.在使用vector变量之前,请进行一些初始化:

    vector->array = NULL;
    vector->len = 0;
    
    Run Code Online (Sandbox Code Playgroud)
  • 此外,您的使用realloc不正确:它不会更改您提供的实际指针,只会更改指向的内存块的大小.您需要自己重新分配指针.请注意,失败时realloc可以返回NULL,所以执行以下操作:

    tmp = realloc(vector->array, size * sizeof(int));
    
    if (tmp != NULL)
    {
        vector->array = tmp;
        vector->len = size; // Changing of length variable
    }
    else handleAllocError();
    
    Run Code Online (Sandbox Code Playgroud)
  • 最后,不要在标题中定义您的函数.这将有效,但最好有一个实现文件vector_int.c来定义标头中声明的函数.

  • "vector"也从未初始化,因此首次调用realloc是未定义的. (2认同)