Home > database >  error when using pointers, dynamically allocating ,struct
error when using pointers, dynamically allocating ,struct

Time:11-23

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

CodePudding user response:

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);

CodePudding user response:

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);
}
  • Related