简体   繁体   中英

Struct passed from pointer shows wrong values

I have a variable struct employee which I initialized on the heap using malloc . I am passing this variable from a pointer using *tmp as shown bellow. The problem is that the values of the variable once passed to the function are wrong. I assume this has to do with the pointer but I can't find the mistake. I guess I am forgeting a basic about pointers. To me, I am passing the variable struct employee pointed by *tmp (and not its address as passing the pointer would do) . Can't see what's wrong in there.

If I check the value inside the createEmployee() function or after calling it, they are right, but they are not in isInformationValid(employee e) . If I change my code and pass a pointer to the function, everything works all right.

typedef struct employee{
  char nom[MAX_NAME_LEN];
  char prenom[MAX_NAME_LEN];
  unsigned short badge;
  unsigned long secret;
  time_t lastAccess;
} employee;

typedef struct maillon maillon;
struct maillon{
  maillon* next;
  maillon* prev;
  employee* e;
};

typedef struct e_list{
  maillon* m;
} e_list;
[...]
int isInformationsValid(employee e){
  int invalidName = (strlen(e.nom) <= 2 || strlen(e.prenom) <= 2); // Problem here
  int invalidBadge = (e.badge < 1000 || e.badge > 9999); // Problem here. e.badge taken as "25789" when I input "1010"
  if(invalidName) { errno = EPERM; perror("Name length must be > 2"); return -1; }
  if(invalidBadge) { errno = EPERM; perror("Badge must be 4 digits"); return -1; }
  return 0;
}

employee* createEmployee(){
  employee* tmp = calloc(1, sizeof(employee*));
  getString("A man needs a last name : ", tmp->nom, MAX_NAME_LEN);
  getString("A man needs a first name : ", tmp->prenom, MAX_NAME_LEN);
  getDigits("Badge (4 digit) : ", &tmp->badge, "%hu");
  getDigits("Secret : ", &tmp->secret, "%lu");
  time_t t = time(NULL);
  tmp->lastAccess = t;
  if(isInformationsValid(*tmp) == -1){ // Passing addr of the struct
    return NULL;
  }
  return tmp;
}

What did I miss? Did I do something wrong in any initialization or am I missing a basic thing about pointers ?

I saw that other questions on stackoverflow has similar questions

The only answers I could reading those other questions was forgotten dynamic allocations on the heap, which is what I think I am doing (maybe the wrong way tho).

EDIT

I was doing it wrong.

您正在分配employee *的规模,但是您应该分配employee (或*tmp )的规模。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM