【发布时间】: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 请将此作为答案,非常完美。