首页 > 解决方案 > realloc():将项目附加到数组时下一个大小无效

问题描述

realloc(): 当我添加时发生无效的下一个大小 *(target_office->packages+(target_office->packages_count-1)) = *pkg;。没有该行不会发生错误。我将数组大小增加了一倍。但这不起作用。

但这*(target_office->packages+(target_office->packages_count)) = *pkg;有效。我不明白为什么。

struct package
{
    char* id;
    int weight;
};

typedef struct package package;

struct post_office
{
    int min_weight;
    int max_weight;
    package* packages;
    int packages_count;
};

typedef struct post_office post_office;

struct town
{
    char* name;
    post_office* offices;
    int offices_count;
};

typedef struct town town;


void send_all_acceptable_packages(town* source, int source_office_index, town* target, int target_office_index) {   
    post_office* source_office = (source->offices+source_office_index);
    post_office* target_office = (target->offices+target_office_index);

    for(int package_i=0; package_i<source_office->packages_count; package_i++){
        package* pkg = source_office->packages+package_i;
        if(pkg->weight>=target_office->min_weight && pkg->weight<=target_office->max_weight){
            target_office->packages_count++;
            target_office->packages = (package *) realloc(target_office->packages,target_office->packages_count);
            *(target_office->packages+(target_office->packages_count-1)) = *pkg;
        }
    }
}

标签: c

解决方案


推荐阅读