c- 在函数中分配结构成员时出错

标签 c function pointers struct member

我正在用 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/

相关文章:

收听 unix 套接字时检查发件人

php - MSSQL 标量值函数 + PHP

python - Python 中的语句和函数有什么区别?

c++ - 为什么不允许指针+指针,但允许指针+整数?

c - 16位模式加载地址

java - 指向 unsigned char* 的 JNA 指针

c - 奇怪的 printf/pthread 错误?

无法链接小型 C 和 Fortran 程序

Javascript:找出数组中是否至少有两个不同的值

c - 释放已分配给 char 指针(字符串)数组的内存。我必须释放每个字符串还是只释放 "main"指针?