简体   繁体   English

C指针分配不正确

[英]C pointers not being assigned properly

I'm creating an array of structs called "mcguffins", and I'm getting a really weird error. 我正在创建一个名为“ mcguffins”的结构体数组,并且遇到了一个非常奇怪的错误。

    //prints the info in a mcguffin 
    void printInfo(int i,struct mcguffin * new) {
      printf("%d \tNum: %d\t Word: %s\n", i, new->num, new->word);
    }

    //creates a new mcguffin
    struct mcguffin * addMG(int n, char * w) {
      printf("Expected output:\n\tNum: %d\tWord: %s\n", n, w);
      struct mcguffin * new;
      new = malloc(sizeof *new);
      new->num = n;
      strncpy(new->word, w, sizeof(char[20]));
      printf("Actual output: \n\t");
      printInfo(1, new);
      return new;
    }

//creates a list of mcguffin pointers, and sets these pointers to new mcguffins
struct mcguffin ** writeList() {
  struct mcguffin ** list = malloc(10 * sizeof(*list));
  list[0] = addMG(2, "Jeter");
  list[1] = addMG(14, "Granderson");
  list[2] = addMG(25, "Teixeira");
  list[3] = addMG(13, "Rodriguez");
  list[4] = addMG(24, "Cano");
  list[5] = addMG(33, "Swisher");
  list[6] = addMG(55, "Martin");
  list[7] = addMG(20, "Posada");
  list[8] = addMG(11, "Gardner");
  list[9] = addMG(42, "Mo");
  return list;
}

For some reason, list[0] and list[1] aren't being assigned to the created structs, but list[2] through list[9] are. 出于某种原因,未将list [0]和list [1]分配给所创建的结构,但将list [2]到list [9]分配给了它们。 addMG works fine, and does create structs for list[0] and list[1], but for some reason when I attempt to use printInfo on them, instead of printing the info on the structs, it prints out a memory address where new->num should go and prints out nothing for new->word. addMG可以正常工作,并且确实为list [0]和list [1]创建了结构,但是由于某些原因,当我尝试在其上使用printInfo时,它不是在结构上打印信息,而是在其中打印了一个内存地址, > num应该走了,什么也不打印出new-> word。

0   Num: 30519472    Word: 
1   Num: 30519600    Word: 
2   Num: 25  Word: Teixeira
3   Num: 13  Word: Rodriguez
4   Num: 24  Word: Cano
5   Num: 33  Word: Swisher
6   Num: 55  Word: Martin
7   Num: 20  Word: Posada
8   Num: 11  Word: Gardner
9   Num: 42  Word: Mo

This is probably some silly error because I'm new to C, but any help would be appreciated. 这可能是一些愚蠢的错误,因为我是C的新手,但任何帮助都将不胜感激。

EDIT: To clarify, mcguffins are declared in a separate header file like so: 编辑:澄清一下,mcguffins声明在一个单独的头文件中,如下所示:

struct mcguffin {

  int num;
  char word[20];
};
new = (struct mcguffin *)malloc(sizeof(struct mcguffin *));
                                                      ^^

You're allocating enough space for a pointer to a mcguffin . 您正在为mcguffin的指针分配足够的空间。 Drop the * . 删除* Better yet, change it to: 更好的是,将其更改为:

new = malloc(sizeof *new);

Your list allocation is likewise wrong. 您的list分配同样是错误的。 You should allocate: 您应该分配:

struct mcguffin **list = malloc(10 * sizeof *list);

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

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