【问题标题】:Dynamically allocating an array of structs in Main and then having a function assign to it [closed]在 Main 中动态分配结构数组,然后为其分配一个函数[关闭]
【发布时间】:2017-03-14 06:45:11
【问题描述】:

我正在为一个项目构建服务器,我需要以有序的方式存储一堆值。我一直在寻找几个小时,我还没有弄清楚如何。

我构建了一个结构如下:

struct WHITEBOARD{
    int line;
    char type;
    int bytes;
    char string[1024];  
} *Server;

然后在我的 main 函数中,我想动态分配内存以创建一个大小为 [argv[1]] 的结构 WHITEBOARD 数组(最终)。我想使用 calloc,在我的研究中我发现了以下内容:

void main()
{
    struct whiteboard (*Server) = (struct whiteboard*) calloc(10, sizeof(*Server));
    (*Server).line = 2;
    printf("Test: %d\n",(*Server).line);
}

这可行,但我似乎不知道如何将 Server 转换为结构数组,以便我可以引用 (*Server)[1].line 并从函数分配给这个堆绑定变量。我打算这样做。

char* doThing(struct whiteboard Server)
{
    (*Server)[1].line = 4;
    return;
}

并且能够从 main 打印新绑定的变量。

这可能是一个愚蠢的问题,但任何帮助都会很棒。谢谢!

【问题讨论】:

标签: c arrays dynamic struct calloc


【解决方案1】:
struct WHITEBOARD{
    int line;
    char type;
    int bytes;
    char string[1024];  
} *Server;

您在全局范围内有一个名为 Server 的变量(指向 struct WHITEBOARD 的指针),因此,您无需在 main 或函数参数内重新声明它,还要注意您在滥用解引用运算符 (*),要访问 (*Server)[1].line = 4; 中的元素 1,只需使用 Server[1].line = 4;

void doThing(void) /* Changed, you promise to return a pointer to char but you return nothing */
{
    Server[1].line = 4;
}

int main(void) /* void main is not a valid signature */
{
    Server = calloc(10, sizeof(*Server)); /* Don't cast calloc */

    Server[1].line = 2;
    doThing();
    printf("Test: %d\n", Server[1].line);
    free(Server);
}

【讨论】:

    【解决方案2】:

    只需摆脱您发明的所有晦涩语法,当您不确定如何做某事时,不要“猜测语法”。

    • 保持结构声明和变量声明分开。
    • 不要使用全局变量。
    • 在没有明显需要时不要使用括号。
    • 不要在同一个表达式中取消引用具有*[] 运算符的指针。
    • 不要转换 calloc 的结果。
    • 不要编写返回类型然后什么都不返回的函数。
    • main() 在托管系统上的签名是int main (void)
    • 总是 free() 分配内存。

    例子:

    #include <stdio.h>
    #include <stdlib.h>
    
    typedef struct 
    {
      int line;
      char type;
      int bytes;
      char string[1024];  
    } whiteboard_t;
    
    
    void do_thing (whiteboard_t* server)
    {
      server[1].line = 4;
    }
    
    int main (void) 
    {
      int n = 10;
      whiteboard_t* server = calloc(n, sizeof(whiteboard_t));
    
      server[0].line = 2;
      printf("Test: %d\n",server[0].line);
    
      do_thing(server);
      printf("Test: %d\n",server[1].line);
    
      free(server);
      return 0;
    }
    

    【讨论】:

    • _t 类型后缀由 POSIX 保留,似乎 OP 想要一个 10 元素的数组,而不是 10 * 10 元素的数组,使用 calloc(n, sizeof(whiteboard_t)); 而不是 calloc(n, sizeof(whiteboard_t[n]));
    • @KeineLust 问题是关于 C 而不是 POSIX。 POSIX 禁止 _t 后缀只是 POSIX 标准中的一个设计缺陷,我对此并不关心。 C 标准积极鼓励将_t 用于类型定义。如果您关心,请向 POSIX 提交缺陷报告。错字已修正,谢谢。
    猜你喜欢
    • 1970-01-01
    • 2013-01-22
    • 1970-01-01
    • 1970-01-01
    • 2020-03-06
    • 2021-10-30
    • 2017-03-30
    • 1970-01-01
    相关资源
    最近更新 更多