1

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

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
Ngoc Anh
  • 21
  • 5

2 Answers2

1

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);
}
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
0

The name nhanVien is not declared. There is declared the type specifier struct nhanVien.

So you need use this name as for example

void input( struct nhanVien *worker,int n){

or

struct nhanVien *worker;

or

worker = (struct nhanVien*)malloc(n*sizeof( struct nhanVien));

This call of scanf

scanf("%d",(worker->code+i));

is incorrect. You need to write either

scanf("%d", &( worker + i )->code);

or

scanf("%d", &worker[i].code);

Also this call of printf

printf("Nhap ma nhanVien : %d \n",*(worker->code+i));

is incorrect. You need to write

printf("Nhap ma nhanVien : %d \n", worker[i].code);
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335