【问题标题】:assignment form incompatible pointer type赋值形式不兼容的指针类型
【发布时间】:2021-04-07 05:48:31
【问题描述】:

我收到一条警告说 assignment from incompatible pointer type 。 我是编程新手,尽了最大的努力,但仍然无法弄清楚。 我收到以下错误: 20 6 D:\DSprograms\practical 2\employees_structure_pointer.c [警告] 来自不兼容指针类型的赋值

/* Accept n employee details using structure and pointer and display their details. */

#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<stdlib.h>

struct employee
{
    int no,salary;
    char name[10],desig[10];
}*ptr;

int main()
{
    int i,n;
    printf("Enter total number of employees: ");
    scanf("%d",&n);
    
    ptr = (int*)calloc(n,sizeof(struct employee));
    printf("\nEnter employee details: \n");
    for(i=0;i<n;i++)
    {
        printf("Enter employee number: ");
        scanf("%d",&(ptr+i)->no);
        printf("Enter name of the employee: ");
        scanf("%s",(ptr+i)->name);
        printf("Enter designation of the employee: ");
        scanf("%s",(ptr+i)->desig);
        printf("Enter salary of the employee: ");
        scanf("%d",&(ptr+i)->salary);
        printf("\n");
    }
    
    printf("Employee details are: \n");
    for(i=0;i<n;i++)
    {
        printf("\nEmployee number is: %d",(ptr+i)->no);
        printf("\nEmployee name is: %s",(ptr+i)->name);
        printf("\nEmployee designation is: %s",(ptr+i)->desig);
        printf("\nEmployee salary is: %d",(ptr+i)->salary);
    }
    return 0;
}

【问题讨论】:

  • ptr 是一个指向struct employee 的指针,但您将malloc 的返回值显式转换为(int *),这是与(struct employee *) 不兼容的指针类型。您不需要这里的演员表; malloc 返回一个void *,这是一个兼容的赋值。所以:ptr = malloc(...);
  • @MOehm 请将此作为答案,非常完美。

标签: c pointers structure


【解决方案1】:

您将ptr 定义为struct employee 的指针:

struct employee
{
    int no,salary;
    char name[10],desig[10];
}*ptr;

然后你分配内存来保存n这样的结构的动态数组:

ptr = (int*)calloc(n,sizeof(struct employee));

函数callocmalloc 返回一个指向void 的指针void *。您将该指针显式转换为指向int 的指针。此分配的右侧现在具有类型 int *

左侧需要struct employee *。你的指针不兼容。

c/malloc 返回 void * 是有原因的:在 C 中,指向 void 的指针可以分配给任何指针类型而无需强制转换。所以你不需要演员表。您的内存分配应该是:

ptr = calloc(n, sizeof(struct employee));

或许

ptr = calloc(n, sizeof(*ptr));

另一方面,C++ 需要显式转换,因此有些人无论如何都会进行转换以兼容 C++ 编译器。如果这样做,则必须强制转换为正确的指针类型。 (显式转换使 malloc 在 C++ 中非常冗长,但无论如何您通常都会使用 new。)

【讨论】:

    猜你喜欢
    • 2019-08-09
    • 2021-06-07
    • 2013-12-12
    • 2019-06-05
    • 2012-03-13
    • 2017-03-26
    • 2014-12-14
    • 2014-07-27
    • 1970-01-01
    相关资源
    最近更新 更多