以下函数是HackerRank挑战的一部分。为什么解引用指针的增量和减量不工作?
void send_all_acceptable_packages(town* source, int source_office_index, town* target, int target_office_index)
{
int pkg_idx;
post_office *src_office = &source->offices[source_office_index];
post_office *tgt_office = &target->offices[target_office_index];
volatile int *src_pkg_cnt = &src_office->packages_count;
volatile int *tgt_pkg_cnt = &tgt_office->packages_count;
for (pkg_idx = 0; pkg_idx < *src_pkg_cnt; pkg_idx++) {
package *pkg = &src_office->packages[pkg_idx];
if (is_acceptable(pkg, tgt_office)) {
move_package(pkg_idx, src_office, tgt_office);
pkg_idx -= 1;
/* Start - This doesn't work */
// *src_pkg_cnt--;
// *tgt_pkg_cnt++;
/* End */
/* Start - This works */
src_office->packages_count--;
tgt_office->packages_count++;
/* End */
}
}
}
操作符优先级。你改变的是指针,而不是指针所指向的值。
应:
(*src_pkg_cnt)--;
(*tgt_pkg_cnt)++;