我正在用 C 语言编写一个程序来查找停止密码中的移位。
作为此过程的一部分,我首先对要解密的消息执行所有可能的移位(0-26),我使用一个结构来存储移位和消息。为此,我将一个结构作为指针传递给函数。但是,当我尝试将结构体的消息成员更改为解密的消息时,出现错误:“strcpy(s->message, cipherText); 行上的“->”类型参数无效(具有“int”)”。 '.
在函数中,我还将一个局部变量分配给结构成员,这工作得很好。
代码:
#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);
}
}
最佳答案
问题是您没有正确关闭 for(int s=...
,并且编译器认为通过 s->
您正在引用循环变量 s
而不是 Solution* s
函数参数。
这就是为什么您会收到无效类型错误。
以下是固定(且缩进更好)的版本:
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);
}
}
} //<--------was missing
strcpy(s->message, cipherText);
}
如果你让编译器警告 -Wshadow
起作用,你得到的信息会非常丰富。
g++
test.cpp:65:30: note: shadowed declaration is here
void Ceaser(struct Solution *s, char cipherText[], int mode) {
clang++
note: previous declaration is here
void Ceaser(struct Solution *s, char cipherText[], int mode) {
icpc
warning #1599: declaration hides parameter "s" (declared at line 65)
for (int s = 0; s <= 26; ++s) {
关于c- 在函数中分配结构成员时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45039864/