[英]Passing pointer to array of 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);
}
}
这是输出:
$ 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
我做了大约一个小时的研究,无法弄清楚为什么这不起作用。 我发现的大多数示例都是针对C ++的,但不是C.(而且我知道我已经包含的许多头文件对于这段代码来说都不是必需的;这只是我原始代码的一部分。)
pass_func
需要一个指向client
的指针数组
void pass_func(client* clients[]);
但你通过它
pass_func(&clients);
指向client
数组的指针。 因此client
clients[i]
client
clients[i]
被解释为pass_func
指向client
的指针,但当然位模式不是指向client
的有效指针,因此您尝试访问不应该访问的内存并获得段错误。
传递一个指针数组,或声明pass_func
void pass_func(client *clients);
(然后在main中传递没有address-operator的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);
}
}
这没关系。
你需要掌握正确的基础知识......
您首先需要了解如何将数组传递给函数:更好地完成此操作
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.