[英]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.