在 Main 中动态分配一个结构数组,然后为其分配一个函数

Dynamically allocating an array of structs in Main and then having a function assign to it

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

我构建了一个结构如下:

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

然后在我的主函数中,我想动态分配内存以创建一个大小为 [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 中打印新绑定的变量。

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

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);
}

简单地摆脱你发明的所有晦涩的语法,当你不确定如何做某事时不要"guess the syntax"。

  • 将结构声明和变量声明分开。
  • 不要使用全局变量。
  • 没有明显需要时不要使用括号。
  • 不要在同一表达式中使用 *[] 运算符取消引用指针。
  • 不要转换 calloc 的结果。
  • 不要编写 return 类型然后 return 什么都没有的函数。
  • 托管系统上 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;
}