【问题标题】:How to get whole structure from function?如何从函数中获取整个结构?
【发布时间】:2022-10-23 16:36:57
【问题描述】:

这是我的代码:

#include <stdio.h>

typedef struct 
{
    char name[100];
    char number[100];
} contact_t;

void empty_array(char *line)
{
    for (int j = 0; line[j] != '\0'; j++)
            {
                line[j] = '\0';     
            }
}

void read_text(contact_t *contact)
{
    int c, cnt = 0;
    int i = 0;
    char line[100];
    do
    {
        c = getchar();
        if ( (c == '\n') || (c == EOF))
        {
            if( cnt % 2 == 0)
            {
                for(int j = 0; line[j] != '\0'; j++)                       
                contact -> name[j] = line[j];
            }
            else
            {
                for(int j = 0; line[j] != '\0'; j++)
                contact -> number[j] = line[j];
            }
            empty_array(line);
            i = 0;
            cnt++;
        }
        line [i] = c;
        i++;
    } while (c != EOF);
}

int main()
{   
    contact_t contact = {"x", "0"};
    int *j_ptr;
     
    read_text(&contact);

    printf("%s", contact.name);    
    printf("%s", contact.number);
    
    return 0;
}

我正在从标准输入中读取一个文本文件(6 行,名称和编号,名称和编号...)。然后我将该文本文件中的每隔一行(从第一行开始)分配给结构contact.name,其余的分配给contact.number。所以我有几个 3 联系结构。我设法只将最后一个传递给 main,因为我不知道如何访问 int cnt 并再次创建一个 for 循环。

这是最后的印刷品给我的:

约翰·格林 254454556

更新: 很抱歉因为我匆忙写这个问题而不够清楚。这段代码是学校项目的一部分,我们不允许使用动态分配的内存或使用 fscanf、fopen、qsort、lsearch、bsearch 和 hsearch 等。基本上,我只想使用指向数组行索引的指针,然后在 main 函数中再次使用 for 循环将所有结构从函数 read_text 传递到程序的 main 函数。

【问题讨论】:

  • minimal reproducible example 会有所帮助。你描述你的代码做什么,没有。
  • 边注:风格上 contact -&gt; name --> contact-&gt;nameline [i] --> line[i]

标签: c pointers structure


【解决方案1】:

几个问题...

  1. main 只提供空间联系人条目
  2. read_text 需要使用动态数组(相对于覆盖同一个条目)
  3. read_text 需要将列表指针和计数返回给调用者(例如main
  4. read_text 中使用的方法有点复杂。

    样式修复:

    1. contact -&gt; name --> contact-&gt;name
    2. list [i] --> list[i]

      这是重构的代码。注释如下:

      #include <stdio.h>
      #include <stdlib.h>
      #include <string.h>
      
      typedef struct {
          char name[100];
          char number[100];
      } contact_t;
      
      int
      read_text(contact_t **listp)
      {
          char buf[1000];
          contact_t *list = NULL;
          char *cp = NULL;
          int cnt = 0;
      
          // loop on input until EOF
          while (fgets(buf,sizeof(buf),stdin) != NULL) {
              // increase size of list
              ++cnt;
              list = realloc(list,sizeof(*list) * cnt);
      
              // handle error
              if (list == NULL) {
                  perror("realloc/increase");
                  exit(1);
              }
      
              // point to current record
              contact_t *contact = &list[cnt - 1];
      
              // get first name
              contact->name[0] = 0;
              cp = strtok(buf," 
      ");
              if (cp == NULL)
                  break;
              strcat(contact->name,cp);
      
              // add separater
              strcat(contact->name," ");
      
              // get last name
              cp = strtok(NULL," 
      ");
              if (cp == NULL)
                  break;
              strcat(contact->name,cp);
      
              // get number
              cp = strtok(NULL," 
      ");
              if (cp == NULL)
                  break;
              strcpy(contact->number,cp);
          }
      
          // trim to actual amount stored (if error)
          if ((cp == NULL) && (cnt > 0)) {
              --cnt;
              list = realloc(list,sizeof(*list) * cnt);
              if (list == NULL) {
                  perror("realloc/trim");
                  exit(1);
              }
          }
      
          // give caller the list pointer
          *listp = list;
      
          return cnt;
      }
      
      int
      main(void)
      {
          int cnt;
          contact_t *list;
      
          cnt = read_text(&list);
      
          // print all entries read in
          for (int idx = 0;  idx < cnt;  ++idx) {
              contact_t *contact = &list[idx];
              printf("'%s' '%s'
      ",contact->name,contact->number);
          }
      
          return 0;
      }
      

      这是我使用的测试输入:

      John Green 254454556
      Fred Smith 8765309
      Bob Jones 99728967341
      Mary Gallagher 4329268757
      

      这是程序输出:

      'John Green' '254454556'
      'Fred Smith' '8765309'
      'Bob Jones' '99728967341'
      'Mary Gallagher' '4329268757'
      

      更新:

      对不起,我应该澄清我不能使用动态分配的内存。 Malloc、calloc 或 fsangf 不可用 – 格雷格尔兹

      好的,没有malloc 等。人。具有讽刺意味的是,我将使用预定义的固定大小数组。但是,决定改用动态数组;-)

      不确定fsangf 是什么。所以,我假设那是fscanf。如果你受到严格限制,也许你应该编辑您的问题并发布你的内容能够并且可以不是利用。

      这是仅使用固定数组的代码:

      #include <stdio.h>
      #include <stdlib.h>
      #include <string.h>
      
      typedef struct {
          char name[100];
          char number[100];
      } contact_t;
      
      #define NLIST       1000
      contact_t list[NLIST];
      
      int
      read_text(contact_t *list,int max)
      {
          char buf[1000];
          char *cp = NULL;
          int cnt = 0;
      
          // loop on input until EOF
          while (fgets(buf,sizeof(buf),stdin) != NULL) {
              // don't overflow the max size
              if (cnt >= max)
                  break;
      
              // point to current record and increase list count
              contact_t *contact = &list[cnt++];
      
              // get first name
              contact->name[0] = 0;
              cp = strtok(buf," 
      ");
              if (cp == NULL)
                  break;
              strcat(contact->name,cp);
      
              // add separater
              strcat(contact->name," ");
      
              // get last name
              cp = strtok(NULL," 
      ");
              if (cp == NULL)
                  break;
              strcat(contact->name,cp);
      
              // get number
              cp = strtok(NULL," 
      ");
              if (cp == NULL)
                  break;
              strcpy(contact->number,cp);
          }
      
          // trim to actual amount stored (if error)
          if ((cp == NULL) && (cnt > 0))
              --cnt;
      
          return cnt;
      }
      
      int
      main(void)
      {
          int cnt;
      
          cnt = read_text(list,NLIST);
      
          // print all entries read in
          for (int idx = 0;  idx < cnt;  ++idx) {
              contact_t *contact = &list[idx];
              printf("'%s' '%s'
      ",contact->name,contact->number);
          }
      
          return 0;
      }
      

【讨论】:

  • 对不起,我应该澄清我不能使用动态分配的内存。 malloc、calloc 或 fsangf 不可用
  • @gregalz 我已经为我的答案添加了更新。
猜你喜欢
  • 2021-07-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-01
  • 1970-01-01
  • 2015-04-22
  • 1970-01-01
相关资源
最近更新 更多