c - 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;
}
}
}
解决方案
推荐阅读
- xml - 是否可以稍后在 XSLT 中声明一个变量并设置值?
- node.js - 在 lambda 函数中使用带有 nodejs 的 https 调用返回数据
- python - python小数给出错误的答案
- java - 使用 BufferedReader 将文件内容存储在 Integer 的 ArrayList 中
- qt - 如何知道qml中的lib版本
- java - 在 JUnit 4 的“gradle test”开始时运行初始化程序
- javascript - JSPDF autotable - 打破大表
- php - PDO 是否仍在为 MySQL 模拟准备好的语句?
- asp.net-mvc - 在视图 MVC 5 上渲染时隐藏输入不起作用
- c++ - 为什么带有type参数的operator()可以在result_of的上下文中应用于type?