C语言Zigzag加密算法行索引负值异常问题求助
问题描述
开发C语言Zigzag加密算法时,遇到向上移动阶段行索引r变为负值的问题,导致程序异常。以下是相关代码、错误执行日志及正确执行日志:
问题代码
#include <stdio.h> int main() { int size = 10; // 输入短语长度 char phrase[] = "ciaomestai"; // 待加密的输入短语 char zzMatrix[3][10]; // 目标矩阵 int r = 0; int isInvert = 0; int cont = 0; int limit = 2; for(int c = 0; c < size; c++) { if(!isInvert){ zzMatrix[r++][c] = phrase[c]; } else { zzMatrix[r--][c] = phrase[c]; } printf("[%c", phrase[c]); printf("isInvert? %d, R:%d --- C:%d]///////", isInvert, r, c); if(cont == limit) { isInvert = !isInvert; limit = (limit == 2) ? 0 : 2; cont = (limit == 2) ? 0:2; } if(!isInvert){ cont++; } else { cont--; } } return 0; }
错误执行日志
[cisInvert? 0, R:0 --- C:0]///////[iisInvert? 0, R:1 --- C:1]///////[aisInvert? 0, R:2 --- C:2]///////[oisInvert? 1, R:1 --- C:3]///////[cisInvert? 1, R:0 --- C:4]///////[oisInvert? 1, R:-1 --- C:5]///////[misInvert? 1, R:-2 --- C:6]///////[eisInvert? 1, R:-3 --- C:7]///////[visInvert? 1, R:-4 --- C:8]///////[aisInvert? 1, R:-5 --- C:9]///////
正确执行日志(输入"hihowareu"时)
[hisInvert? 0, R:0 --- C:0]///////[iisInvert? 0, R:1 --- C:1]///////[hisInvert? 0, R:2 --- C:2]///////[oisInvert? 1, R:1 --- C:3]///////[wisInvert? 1, R:0 --- C:4]///////[aisInvert? 0, R:1 --- C:5]///////[risInvert? 0, R:2 --- C:6]///////[eisInvert? 0, R:1 --- C:7]///////[uisInvert? 1, R:0 --- C:8]///////
问题原因
当前代码用cont和limit变量判断方向切换时机,逻辑冗余且存在错误:
- 向上移动时(
isInvert=1),cont递减后未及时触发方向切换,导致程序持续执行r--操作,最终使r变为负值。 - 方向切换的条件判断与
cont的更新顺序不匹配,无法在r到达顶部边界(r=0)时及时切换回向下移动状态。
修复方法
简化方向控制逻辑,直接通过行索引r的边界值(顶部0、底部2)判断是否需要切换方向,去掉冗余的cont和limit变量:
修复后的代码
#include <stdio.h> int main() { int size = 10; // 输入短语长度 char phrase[] = "ciaomestai"; // 待加密的输入短语 char zzMatrix[3][10]; // 目标矩阵 int r = 0; int direction = 1; // 1表示向下移动,-1表示向上移动 for(int c = 0; c < size; c++) { zzMatrix[r][c] = phrase[c]; // 保持原日志格式打印 printf("[%c", phrase[c]); printf("isInvert? %d, R:%d --- C:%d]///////", direction == -1, r + direction, c); // 更新行索引 r += direction; // 到达边界时切换方向 if(r == 2 || r == 0) { direction *= -1; } } return 0; }
修复逻辑说明
- 用
direction变量控制行索引变化方向:1表示r递增(向下),-1表示r递减(向上)。 - 每次给矩阵赋值后,先更新
r,再检查是否到达顶部(r=0)或底部(r=2)边界,到达则反转方向。 - 日志打印中,
isInvert对应direction == -1,R的值为更新后的r(与原日志格式保持一致)。
内容的提问来源于stack exchange,提问作者Conta

