将指针传递给struct数组

fac*_*918 4 c arrays struct

我正在尝试将指针传递给struct数组.这段代码应该创建一个struct数组,写入struct中的vars,然后将它们打印出来(有效).然后我想将一个struct数组的指针传递给另一个函数并打印出struts数组.

#define PORT_NUMBER 5100
#define MAX_CLIENTS 5

#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <pthread.h>

typedef struct thread_args
 {
    int client_number;
    int connected;
    char client_name[1024];
} client;

void pass_func(client* clients[])

int main()
{
  struct thread_args clients[MAX_CLIENTS];
  int i;

  for(i =0; i < MAX_CLIENTS; i++)
  {
  clients[i].client_number=i;
  strcpy(clients[i].client_name, "BOBBY");
  }

    for(i =0; i < MAX_CLIENTS; i++)
  {
     printf("%d | %s\n", clients[i].client_number=i, clients[i].client_name);
  }

  printf("\n\n");
  pass_func(&clients);
}

void pass_func(client* clients[])
{
  int i;
  for(i =0; i < MAX_CLIENTS; i++)
  {
     printf("%d | %s\n", clients[i]->client_number=i, clients[i]->client_name);
  }
}
Run Code Online (Sandbox Code Playgroud)

这是输出:

$ gcc TEST.c -lpthread -o TEST.out
TEST.c: In function ‘main’:
TEST.c:41:3: warning: passing argument 1 of ‘pass_func’ from incompatible pointer type [enabled by default]
TEST.c:22:6: note: expected ‘struct thread_args **’ but argument is of type ‘struct thread_args (*)[5]’

$ ./TEST.out 
0 | BOBBY
1 | BOBBY
2 | BOBBY
3 | BOBBY
4 | BOBBY


Segmentation fault
Run Code Online (Sandbox Code Playgroud)

我做了大约一个小时的研究,无法弄清楚为什么这不起作用.我发现的大多数示例都是针对C++的,但不是C.(而且我知道我已经包含的许多头文件对于这段代码来说都不是必需的;这只是我原始代码的一部分.)

Dan*_*her 13

pass_func 期望一个指针数组 client

void pass_func(client* clients[]);
Run Code Online (Sandbox Code Playgroud)

但你通过它

pass_func(&clients);
Run Code Online (Sandbox Code Playgroud)

指向clients 数组的指针.所以它client clients[i]被解释为指向clientin 的指针pass_func,但当然位模式不是有效的指针client,因此你试图访问你不应该访问的内存并获得段错误.

传递一个指针数组,或者声明 pass_func

void pass_func(client *clients);
Run Code Online (Sandbox Code Playgroud)

(然后pass_func(clients)在main中没有address-operator的情况下传递).

但是,编译器会警告您传递不兼容的指针类型.