小编Але*_*Рак的帖子

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

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" …
Run Code Online (Sandbox Code Playgroud)

c memory-management function std

2
推荐指数
1
解决办法
3732
查看次数

标签 统计

c ×1

function ×1

memory-management ×1

std ×1