cstructdeclarationmember-access

error when using pointers, dynamically allocating ,struct


My code don't run ,how can I fix it i think i don't understand where i am wrong error when using pointers, dynamically allocating ,struct

#include"stdio.h"
#include"stdlib.h"
#include"string.h"
struct nhanVien{
    int code;
    char name[50];
    char sex[50];
    int numb;
    int wage;
};
void input(nhanVien *worker,int n){
    for(int i=0;i<n;i++){
        printf("Nhap ma nhanVien : ");
        scanf("%d",(worker->code+i));
        
    }
}
int main(){
    nhanVien *worker;
    int n;
    printf("Nhap so luong nhan vien : ");
    scanf("%d",&n);
    worker = (nhanVien*)malloc(n*sizeof(nhanVien));
    input(worker,n);
    for(int i=0;i<n;i++){
        printf("Nhap ma nhanVien : %d \n",*(worker->code+i));
        
    }
    free(worker);
    
}

Invalid type argument of unary '*' (have 'int') Error in C this is images enter image description here


Solution

  • I found a number of issues in your code, worker->code+i should be worker[i].code; you're missing typedef on the struct type. Basically, you want something like

    #include"stdio.h"
    #include"stdlib.h"
    #include"string.h"
    
    typedef struct {
        int code;
        char name[50];
        char sex[50];
        int numb;
        int wage;
    } nhanVien;
    
    void input(nhanVien *worker,int n) {
        for(int i=0; i<n; i++) {
            printf("Nhap ma nhanVien : ");
            scanf("%d", &worker[i].code);
        }
    }
    
    int main() {
        nhanVien *worker;
        int n;
        printf("Nhap so luong nhan vien : ");
        scanf("%d",&n);
        worker = (nhanVien*)malloc(n*sizeof(nhanVien));
        input(worker,n);
        for(int i=0; i<n; i++) {
            printf("Nhap ma nhanVien : %d \n",worker[i].code);
        }
        free(worker);
    }