1

Here is some code for a data structure:

struct node {
    char* command;
    char** prereq;
    prereq = malloc(100*sizeof(char*));
    for (int i = 0; i<100; i++)
    {
        prereq[i]=malloc(80);
    }
    Node *next;
    char *targ;
    int isUpdated;
};

However, when I try to run the program with this structure in it, I'm getting this error:

error: expected specifier-qualifier-list before ‘prereq’

After reading up on this error, it looks like it's most common when someone tries to create a linked list without declaring 'struct' inside the structure. However, I'm baffled as to how it applies to my structure.

If it helps, I have this in the header:

typedef struct node Node;
4

1 回答 1

0

您不能for在结构定义中编写循环!或者任务,来吧。甚至 C++ 也不会接受它的书面形式。

typedef struct node Node;
struct node
{
    char  *command;
    char **prereq;
    Node  *next;
    char  *targ;
    int    isUpdated;
};

那应该没问题(尽管它是我的代码,但我会使用typedef struct Node Node;and struct Node { ... };— 结构标签与 typedef 名称位于不同的命名空间中,因此没有问题)。

然后,您可以将初始化程序代码放在单独的函数initnode()或类似的东西中:

int initnode(Node *node)
{
    node->command = 0;
    node->next = 0;
    node->targ = 0;
    node->isUpdated = 0;
    if ((node->prereq = malloc(100*sizeof(char*))) == 0)
        return -1;
    for (int i = 0; i < 100; i++)
    {
        if ((node->prereq[i] = malloc(80)) == 0)
        {
            for (int j = 0; j < i; j++)
                 free(node->prereq[j]);
            free(node->prereq);
            node->prereq = 0;
            return -1;
        }
    }
    return 0;
}
于 2013-09-17T23:42:04.567 回答