【问题标题】:C Incompatible pointer type message appears to list identical pointer types for expected and actualC 不兼容的指针类型消息似乎列出了预期和实际的相同指针类型
【发布时间】:2019-08-06 03:45:55
【问题描述】:

我正在尝试编写代码来为结构数组动态分配内存。我想将与堆内存空间关联的指针传递给另一个函数以供进一步使用。以下代码示例是我想要做的一个粗略示例(为简洁起见):

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <openssl/sha.h>
#include <time.h>

struct password_struct;
void create_password(char password_seeds[], struct password_struct* user_passwords);

void main() {


    char password_seeds[100];
    int num_passwords = 5;
    struct password_struct {
        char password[17];
        char hash[65];
        int entropy;
    };


    struct password_struct *user_passwords = malloc(num_passwords * sizeof(struct password_struct));

    create_password(password_seeds, user_passwords);
    free(user_passwords);
}


void create_password(char password_seeds[], struct password_struct* user_passwords){

}

当我尝试编译它时,我收到以下错误:

In function ‘main’:
     c:24:5: warning: passing argument 2 of ‘create_password’ from incompatible pointer type [enabled by default]
     create_password(password_seeds, user_passwords);
     ^
     c:8:6: note: expected ‘struct password_struct *’ but argument is of type ‘struct password_struct *’
     void create_password(char password_seeds[], struct password_struct* user_passwords);
          ^

这似乎为实际和预期的指针类型列出了相同的指针类型。任何帮助将不胜感激。

【问题讨论】:

  • 为什么要在main()里面定义struct?

标签: c arrays pointers struct compiler-errors


【解决方案1】:

这是因为,password_struct 结构体的定义在 main() 内部,而在范围之外是不可见的。

在文件范围内移动结构定义(main() 或任何其他函数之外)。

也就是说,看看这个:What are the valid signatures for C's main() function?

【讨论】:

    【解决方案2】:

    您有两种不同的struct password_struct 类型——一种在全局范围内定义,另一种在主范围内定义。尽管它们具有相同的名称,但由于位于不同的范围内,它们最终成为两种不相关的类型。该函数被声明为使用指向全局函数的指针,但在 main 中,您使用指向本地函数的指针。

    【讨论】:

      【解决方案3】:

      struct password_struct *user_passwords = malloc(num_passwords * sizeof(struct password_struct));

      这里您正在为password_struct 创建内存 malloc 函数返回泛型指针,因此类型转换很重要,因此您可以将泛型指针转换为password_Struct。所以试试这个

      struct password_struct *user_passwords = (struct password_struct*)malloc(num_passwords * sizeof(struct password_struct));

      这条线可以解决你的问题。

      【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-11-12
      • 1970-01-01
      • 2013-11-06
      • 1970-01-01
      • 2021-11-23
      相关资源
      最近更新 更多