Search code examples
cpointersstructure

assignment form incompatible pointer type


I am getting a warning saying assignment from incompatible pointer type . I am new to programming and tried my best but still couldn't figure it out. I am getting the following error: 20 6 D:\DS programs\practical 2\employees_structure_pointer.c [Warning] assignment from incompatible pointer type

/* 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;
}

Solution

  • You define ptr as a poiner to a struct employee:

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

    Then you allocate memory to hold a dynamic array of n such structs:

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

    The functions calloc and malloc return a pointer to void, void *. You cast that pointer explicitly to a pointer to int. The right-hand side of this assignment now has type int *.

    The left-hand side expects a struct employee *. There lies your pointer incompatibility.

    There is a reason why c/malloc returns a void *: In C, a pointer to void can be assigned to any pointer type without cast. So you don't need the cast. Your memory allocation should be just:

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

    or perhaps

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

    On the other hand, C++ requires an explicit cast, so some people do cast anyway to be compatible to C++ compilers. If you do that, you must cast to the correct pointer type. (The explicit cast makes malloc quite verbose in C++, but you will usually use new instead anyway.)