2

私は持っている:

typedef struct table {

int size;

} Table;

したがって、メソッドのパラメーターは次のとおりです。

Table **table

しかし、私がするとき:

table->size = 5;

また:

*table->size = 5;

それは機能せず、私のフラグは私にエラーを与えています: request for member 'size' in something not a structure or union

助けてください。

4

3 に答える 3

4

奇妙な間接化をすべて回避するには、ローカル変数を使用して移動する方が簡単です。

void myfunc(Table ** my_table) {
    Table * ptable = *my_table;
    ptable->size = 5;

    /*  etc  */
}

しかし、他の人が指摘し(*table)->size = 5たように、などは同じことをします。

指されているものを変更する必要がある場合は、次のようにします。

void myfunc(Table ** my_table) {
    Table * ptable = malloc(sizeof(*ptable));

    /*  Do stuff with new table, then update argument  */

    *my_table = ptable;
}

後者の例を次に示します。

#include <stdio.h>
#include <stdlib.h>

typedef struct table {
    int size;
} Table;

int create_table(Table ** table, int size) {
    Table * new_table = malloc(sizeof(*new_table));
    if ( new_table == NULL ) {
        return -1;
    }

    new_table->size = size;

    *table = new_table;
    return 0;
}

int main(void) {
    Table * my_table;

    if ( create_table(&my_table, 5) == -1 ) {
        fprintf(stderr, "Couldn't allocate memory for new table.\n");
        return EXIT_FAILURE;
    }

    printf("New table size is %d\n", my_table->size);

    free(my_table);

    return 0;
}

もちろん、新しく作成されたテーブルにa を返すだけでもかまいません、あなたの場合、その関数は return として宣言されています。さまざまな理由が考えられますが、上記では、エラー コードが返されると想定しています。私たちが知っているように、C の関数は 1 つの値しか返すことができません。、そのアドレスを渡す必要があるため、関数は.create_table()Table *intintTable *Table *Table *Table **

于 2013-10-27T01:22:21.997 に答える
2

The dereference operator (*) has a lower priority, so this:

*table->size

is evaluated as:

*(table->size)

Since table is a pointer to a pointer, and pointers can't have members, you get an error. What you need is:

(*table)->size = 5;

Now, *table is evaluated first, yielding a pointer to a Table. -> is then able to be applied to it.

Unrelated:

I noticed that you use different identifiers for the struct name and for its typedef. This isn't necessary. You can just use:

typedef struct Table {
    int size;
} Table;
于 2013-10-27T01:20:59.413 に答える
0

table_t **mytable doを使用する場合(*mytable)->size = 5;

table_t *mytable doを使用する場合mytable->size = 5;

typedef struct /* table */ {
    int size;
} table_t;  //conventional naming

int main() {
    table_t *mytable = malloc((sizeof *mytable)); //avoid "Access Violation", by allocating memory
    mytable->size = 5; //set size to '5'
    return 0; //conventional return
}
于 2013-10-27T01:25:35.213 に答える