2012-04-21 31 views
4

構造体の配列へのポインタを渡そうとしています。このコードは構造体の配列を作成し、構造体の変数に書き込んだ後に出力します(動作します)。次に、その構造体の配列のポインタを別の関数に渡して、ストラットの配列を出力したいと思います。構造体の配列へのポインタの受け渡し

#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ではありません。(もちろん、私がインクルードしたヘッダーファイルの多くは、このコードでは必要ではありませんが、これは私のオリジナルコードの単なる部分です)。

+0

どのように通過良くpass_funcについて(&クライアント[0]) – TJD

+0

@ TJD - それは私に同じ振る舞いを与えます。 – faction918

答えて

12

pass_funcclient

void pass_func(client* clients[]); 

へのポインタの配列を期待していますがclientの配列にそれを

pass_func(&clients); 

ポインタを渡します。したがってclientclients[i]clientへのポインタとして解釈されますが、pass_funcのビットパターンはclientへの有効なポインタではありません。そのため、あなたはセグメンテーション違反となるメモリにアクセスしようとしています。

ポインタの配列を渡す、またはpass_func

void pass_func(client *clients); 

を宣言する(そして主にアドレスオペレータなしpass_func(clients)を渡す)のいずれか。

あなたのコンパイラは、互換性のないポインタ型を渡すことについて警告しました。

+0

警告: "TEST.c:41:3:警告:互換性のないポインタ型から 'pass_func'の引数1を渡します。" – huon

+0

ああ、そうです。完全にそれを逃した。なぜ人々がコンパイラの警告に耳を傾けないのかという疑問が生じます。 –

+0

私は同意する、彼らは非常に便利です。 (特にGCCの方が、あまり経験がなければ、警告はかなり不安定になるかもしれませんが)。 – huon

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

これは問題ありません。

1

あなたが最初の配列は最初の関数に渡されるかを理解する必要があります...右

を基本を取得する必要があります: this

関連する問題