2

I have:

typedef struct table {

int size;

} Table;

So I have a parameter for a method as:

Table **table

But when I do:

table->size = 5;

OR:

*table->size = 5;

It doesn't work and my flags is giving me the error: request for member 'size' in something not a structure or union

Please help.

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

当然,您可以create_table()只将 a 返回Table *到新创建的表,但在您的情况下,该函数已被声明为返回int。可能有多种原因,但在上面我只是假设它是返回一个错误代码。众所周知,C语言中的函数只能返回一个值,所以如果它返回一个int它就不能返回一个Table *,所以获得新指针的唯一方法是修改一个参数,如果你想修改一个Table *,你必须传递那个地址Table *,所以你的函数必须接受一个Table **.

于 2013-10-27T01:22:21.997 回答
2

取消引用运算符 ( *) 的优先级较低,因此:

*table->size

被评估为:

*(table->size)

由于table是指向指针的指针,并且指针不能有成员,因此会出现错误。你需要的是:

(*table)->size = 5;

现在,*table首先评估,产生一个指向 a 的指针Table->然后可以应用于它。

无关:

我注意到您对结构名称和它的 typedef 使用了不同的标识符。这是没有必要的。您可以使用:

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

如果使用table_t **mytable(*mytable)->size = 5;

如果使用table_t *mytablemytable->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 回答