【问题标题】:Simple STRUCT program beginner QUESTIONS简单的 STRUCT 程序初学者问题
【发布时间】:2013-10-24 09:27:13
【问题描述】:

所以我刚开始学习 C 中的结构类型,但我有点困惑。我正在处理一个很长的程序,我不确定如何使用函数内部的静态变量(例如称为 nextinsert)将姓名和年龄插入到数组中下一个未使用的元素中记住下一个未使用的元素在哪里。

这是我的插入函数代码。

static void insert (struct person people[], char *name, int age)
{
  static int nextfreeplace = 0;
  static int nextinsert = 0;
  /* put name and age into the next free place in the array parameter here */

【问题讨论】:

  • 在你的主目录中传递一个指向索引people 的指针:insert (&people[i], names[i], ages[i]);。由于您在该循环中有一个计数器,因此让调用您的insert 的函数负责找出people 中的下一个元素是什么。

标签: c arrays struct structure


【解决方案1】:

对于您的问题“如何插入姓名和年龄”,请使用:

strcpy(people[nextfreeplace],name);
people[nextfreeplace].age = age;

您可能需要为 strcpy 添加 string.h

【讨论】:

    【解决方案2】:

    为什么不让它变得更简单:与其尝试跟踪insert 函数中的索引,不如在main 函数中找到索引。因此:

    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>
    
    /* these arrays are just used to give the parameters to 'insert',
       to create the 'people' array */
    #define HOW_MANY 7
    #define MAXSTRLEN 32
    
    /* declare your struct for a person here */
    struct person
    { 
        char name [MAXSTRLEN];
        int age;
    };
    
    static void insert (struct person *people, char *name, int age)
    {
      strncpy(people->name, name, MAXSTRLEN);
      people->age = age;
    
    }
    
    int main(int argc, char **argv) {
      // Move arrays here; if they are global instead, 
      // there would be need to pass name and age to insert()
      char *names[HOW_MANY]= {"Simon", "Suzie", "Alfred", "Chip", "John", "Tim",
                  "Harriet"};
      int ages[HOW_MANY]= {22, 24, 106, 6, 18, 32, 24};
      /* declare the people array here */
      struct person people[12]; 
    
      int i;
      for (i =0; i < HOW_MANY; i++) 
      {
        insert (&people[i], names[i], ages[i]);
      }
    
      /* print the people array here*/
      for (i =0; i < HOW_MANY; i++)
      {
         printf("%s\n", people[i].name);
         printf("%d\n", people[i].age);
      }
    
      return 0;
    }
    

    people-&gt;name 语法是(*people).name 的简写。也就是说,您取消引用指针以获取实际结构(*people),然后访问结构编号;由于运算符优先规则,您需要在*people 周围加上括号。

    我不确定您对指针有多熟悉,但在 C 中,这很常见(将指向结构的指针传递给函数,然后在该函数中使用 structure-&gt;member

    当然,如果您的整个“练习”都围绕着学习静态变量,那么这可能没有什么价值。但是我在这里所拥有的可能比在函数内部保留一个静态变量来进行数组索引更可取。

    【讨论】:

    • 嗨,谢谢你的想法 Evert。的确,你的方法确实比我的好很多。但是,我不太明白“->”是什么意思(例如 people->age = age;)。
    • 另外,由于某种原因,您的程序版本和我的程序版本都给了我一些非常奇怪的编译错误:您的版本:arrays2.c:13:错误:灵活的数组成员不在结构数组的末尾.c:17:错误:声明说明符arrays2.c中有两种或多种数据类型:在函数'insert'中:arrays2.c:21:错误:')'标记之前的预期表达式arrays2.c:24:警告:不返回返回非空数组2.c的函数中的语句:在函数'main'中:arrays2.c:42:错误:预期';'在')'标记之前
    • 对不起,我很懒,并没有真正检查我的程序。一些修复(分号,正确定义 MAXSTRLEN 并删除我从你那里复制的一些错字;-) 应该可以解决问题。
    • 根据您的问题,还添加了一些关于结构指针的信息。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-05
    • 2020-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多