简体   繁体   English

从指针传递的结构显示错误的值

[英]Struct passed from pointer shows wrong values

I have a variable struct employee which I initialized on the heap using malloc . 我有一个变量struct employee ,我在堆上使用malloc进行了初始化。 I am passing this variable from a pointer using *tmp as shown bellow. 我正在使用*tmp从指针传递此变量,如下所示。 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) . 对我来说,我正在传递*tmp指向变量struct employee (而不是像指针一样传递其地址) 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) . 如果我在createEmployee()函数内部或在调用它后检查该值,则它们是正确的,但不在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 我看到关于stackoverflow的其他问题也有类似的问题

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 )的规模。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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