0
typedef struct
{
    char struct_variable_1a[10];
    char struct_variable_1b[12];
} struct1;

typedef struct
{
    char struct_variable_1a[10];
    char struct_variable_1b[12];
    int struct_variable_2c;
} struct2;

typedef struct1 *struct1_ptr;
typedef struct2 *struct2_ptr;



static void sampleFunction(struct1_ptr valueToInsert){
//this code does some stuff here
}


int main(){

struct1_ptr struct1_var = (struct1_ptr) malloc(sizeof(struct1));
strcpy(struct1_var->struct_variable_1a, "some value");
strcpy(struct1_var->struct_variable_1b, "some value");

sampleFunction(struct1_var);

return 0;
}

C programming上記のようにサンプルコードがあります。メソッドでは、メソッド呼び出し用mainの型の変数を渡そうとしています。これは魅力のように機能します。しかし、 type の変数を渡したい場合、コンパイラはエラーをスローします。基本的に、私は Java 開発者です。一般に、このメソッドをそのパラメーターの任意の変数型に再利用したいと考えています。これで私を助けてください。struct1_ptrsampleFunctionstruct2_ptrsampleFunction

4

3 に答える 3

2

関数を次から変更します。

static void sampleFunction(struct1_ptr valueToInsert){
//this code does some stuff here
}

に:

static void sampleFunction(void* valueToInsert){
//this code does some stuff here
}

構造体の型を識別したい場合は、構造体のサイズを含む 2 番目のパラメーターを関数に追加します。

//編集:
関数内で、変数を使用したい構造にキャストし直す必要があります。例えば:

strcpy(((struct1_ptr)valueToInsert)->struct_variable_1a, "some value");
于 2013-08-27T13:52:26.000 に答える