【发布时间】:2017-07-11 16:20:57
【问题描述】:
我正在用 C 语言编写一个程序来查找停止者密码中的转换。
作为其中的一部分,我首先对要破译的消息执行所有可能的移位,0-26,我使用一个结构来存储移位和消息。为此,我将结构作为指针传递给函数。但是,当我尝试将结构的消息成员更改为解密消息时,我收到错误:'strcpy(s->message, cipherText); '。
在函数中,我还为结构成员分配了一个局部变量,这工作正常。
代码:
#include <stdio.h>
#include <string.h>
#define ENCRYPT 0
#define DECRYPT 1
struct Solution {
int key;
char message[];
};
void Ceaser(struct Solution *s, char cipherText[], int mode);
void main(){
struct Solution solutions[26];
char cipherText[] = "lipps, asvph.";
for (int i = 0; i <= 26; ++i) {
solutions[i].key = i;
Ceaser(&solutions[i], cipherText, DECRYPT);
printf("Key: %d\tPlain text: %s\n", solutions[i].key,
solutions[i].message);
}
}
void Ceaser(struct Solution *s, char cipherText[], int mode) {
int len = strlen(cipherText);
int c;
int key = s->key;
for (int s = 0; s <= 26; ++s) {
if (mode == DECRYPT) {
key *= -1;
}
for (int i = 0; i < len; ++i) {
c = cipherText[i];
if (c >= 'A' && c <= 'Z') {
cipherText[i] = 'A' + ((c + key - 'A') % 26);
} else if (c >= 'a' && c <= 'z') {
cipherText[i] = 'a' + ((c + key - 'a') % 26);
}
}
//Error occurs below
strcpy(s->message, cipherText);
}
}
【问题讨论】:
-
s->message:char message[];没有空格。 -
问题是你有两个名为 s 的变量。内部的 int s 遮住了外部的 Solution *s。如果您使用 gcc,则 -Wshadow 标志非常适合定位此类问题。
-
@BjornA。谢谢,虽然这很简单,但我不敢相信我没有注意到冲突。也感谢编译器提示。
标签: c function pointers struct member