简体   繁体   English

C-创建和使用结构数组? 错误:预期标识符或'['标记前的'('

[英]C - Creating and using an struct array? error: expected identifier or '(' before '[' token

So I am trying to build and use a struct array in C, and I am encountering a few errors of which I cannot resolve. 因此,我试图在C中构建和使用一个struct数组,但遇到一些我无法解决的错误。 The code that I have is: 我拥有的代码是:

int numWords = 10;

typedef struct
{
    char* word;
    int count;
} wordsCount;

wordsCount words[numWords];

words[0].word = "Hello";
words[0].count = 1;

First of all, when using the gcc compiler in Unix, I receive an warning, when compiling with the -Wall -pedantic -ansi flags, which reads warning: ISO C90 forbids variable length array 'words' [-Wvla] . 首先,在Unix中使用gcc编译器时,使用-Wall -pedantic -ansi标志进行编译时会收到警告, warning: ISO C90 forbids variable length array 'words' [-Wvla] And for the last two lines of my code snippet, I receive the error: error: expected identifier or '(' before '[' token . 对于我的代码片段的最后两行,我收到错误: error: expected identifier or '(' before '[' token

Could anybody tell me why I am getting these errors? 谁能告诉我为什么会出现这些错误? I've Googled many different typedef and struct examples, and mine mirrors that of those examples. 我已经用Google搜索了许多不同的typedef和struct示例,而我的镜像类似于这些示例。


EDIT: Thank you all for the suggestions. 编辑:谢谢大家的建议。 I decided to edit my post instead of responding to each individual comment to provide some clarification of my question. 我决定编辑我的帖子,而不是回答每个评论以澄清我的问题。 So, I now understand that you can't use variable length arrays in C. I can't officially accept any of the provided answers because my problem still exists, so a clearer explanation of what I am trying to do is warranted. 因此,我现在知道您不能在C中使用可变长度数组。由于我的问题仍然存在,因此我无法正式接受任何提供的答案,因此,对于我想做的事情有一个更清晰的解释是必要的。

I am creating a program which counts the occurrences of each word in a text file and prints it out in ASCII order. 我正在创建一个程序,该程序计算文本文件中每个单词的出现并以ASCII顺序将其打印出来。 For example, if the text file contains the following text: "Buffalo buffalo Buffalo buffalo buffalo buffalo Buffalo buffalo" is a grammatically correct sentence. 例如,如果文本文件包含以下文本: "Buffalo buffalo Buffalo buffalo buffalo buffalo Buffalo buffalo" is a grammatically correct sentence. , the output of the program shall be: ,程序的输出应为:

Buffalo - 3 a - 1 buffalo - 5 correct - 1 sentence - 1 . Buffalo - 3 a - 1 buffalo - 5 correct - 1 sentence - 1

The words themselves are already stored into an array. 单词本身已经存储在数组中。 So I want to create an array of structs that contain both the word and the count. 因此,我想创建一个既包含单词又包含计数的结构数组。 I've revised my program to account for dynamically allocated memory. 我已经修改了程序,以解决动态分配的内存问题。 My updated code is: 我更新的代码是:

typedef struct
{
    char* word;
    int count;
} wordsCount;

wordsCount** words = malloc(sizeof(*words) * numWords);

words[0]->word = "Hello";
words[0]->count = 2;

printf("%s - %d\n", words[0]->word, words[0]->count);

*Note that numWords is an integer that changes according to how large the text file is. *请注意, numWords是一个整数,会根据文本文件的大小而变化。

It compiles fine; 它可以编译。 however, I receive a seg fault at the first assignment statement words[0]->word = "Hello"; 但是,在第一个赋值语句words[0]->word = "Hello";收到段错误words[0]->word = "Hello"; .

Am I wrong to assume that I can create a pointer to a pointer to structs? 我以为可以创建指向结构的指针是我的错吗? I thought the `->' operator does the deference of the struct pointer, and then point to the member "word." 我以为'->'运算符会遵从struct指针,然后指向成员“ word”。 I do not understand why I am seg faulting. 我不明白为什么我会错。 Any help would be appreciated. 任何帮助,将不胜感激。 If making this edit warrants a new thread, please let me know so I can move it. 如果进行此编辑需要新的主题,请告诉我,以便我进行移动。 Thanks. 谢谢。

EDIT 2 I figured out the problem - I was pointer-happy and used way too many pointers to do what I want. 编辑2我想出了问题-我很满意指针,并且使用太多指针来做我想要的事情。 I changed wordsCount** words = malloc(sizeof(*words) * numWords); 我更改了wordsCount** words = malloc(sizeof(*words) * numWords); to wordsCount* words = malloc(sizeof(*words) * numWords); wordsCount* words = malloc(sizeof(*words) * numWords); . And then I realized I was doing necessary dereferencing when I did words[0]->word = "Hello"; 然后我意识到我在执行words[0]->word = "Hello";时正在做必要的引用words[0]->word = "Hello"; , so I changed it to words[0].word = "Hello"; ,所以我将其更改为words[0].word = "Hello"; , and it works perfectly. ,并且效果很好。 Thanks for the help, guys. 谢谢大家的帮助。 I'm not sure how to close a thread, or if I should post an answer to my own question? 我不确定如何关闭线程,还是应该发布自己问题的答案? But this thread is now closed. 但是此线程现在已关闭。

#define NUM_WORDS 10

typedef struct
{
  char* word;
  int count;
} wordsCount;

wordsCount words[NUM_WORDS];

This will sufficiently allocate the memory you will need in order to start assigning values. 这样可以充分分配您需要的内存,以便开始分配值。

The compiler needs to know how big the 'words' array should be, so when it comes across your array initialization, it expects to find a size between the brackets. 编译器需要知道'words'数组应该有多大,因此在遇到数组初始化时,它希望在括号之间找到一个大小。 But it finds the 'numWords' variable instead and it can't use that. 但是它找到了'numWords'变量,因此不能使用它。 The preprocessor will not replace 'numWords' with '10'. 预处理器不会将“ numWords”替换为“ 10”。 It will do so when you change this 当您更改此设置时,它将这样做

int numWords = 10;

to this 对此

#define numWords 10

That should work. 那应该工作。 The preprocessor will then replace every instance of the word 'numWords' in your code with '10', so that the array initialization will read: 然后,预处理器会将代码中单词'numWords'的每个实例替换为'10',以便数组初始化为:

wordsCount words[10];

There are two main problems. 主要有两个问题。

The first, ably identified by the other answers, is that you can't use a VLA at global scope. 第一个是其他答案明确指出的,那就是您不能在全局范围内使用VLA。 Since numWords is an int variable, it is not a constant and array dimensions at file scope must be constants. 由于numWords是一个int变量,因此它不是常量,并且文件范围内的数组维数必须是常量。

I'd recommend: 我建议:

enum { numWords = 10 };

See also static const vs #define in C . 另请参见C中的static const vs #define

The second problem is that you are writing assignments at global scope, and that is not allowed either. 第二个问题是您正在全局范围内编写分配,这也是不允许的。 You can provide an initializer, though: 您可以提供一个初始化程序:

enum { numWords = 10 };

typedef struct
{
    char* word;
    int count;
} wordsCount;

static wordsCount words[numWords] =
{
    { "Hello", 1 },
};

You wouldn't want to let code outside this file access your variables, would you? 您不想让该文件之外的代码访问您的变量,对吗?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 c代码中的错误:预期标识符或'('''''''之前的标记 - error in c code: expected identifier or '(' before '{' token C-错误预期标识符'('''''''令牌 - C- error expected identifier or '(' before '.' token C-“错误:预期标识符或'['标记前的'('” - C - “Error: Expected identifier or '(' before '[' token” 错误:C 中“->”标记之前的预期标识符或“(” - Error: expected identifier or ‘(’ before ‘->’ token in C 指向C中的结构-错误:“ *”标记之前的预期“)” - Pointing to struct in C - error: expected ')' before '*' token 错误:预期的';',标识符或'('在'struct'之前 - error: expected ‘;’, identifier or ‘(’ before ‘struct’ 错误:预期标识符或 '(' before ')' 标记 - error: expected identifier or ‘(’ before ‘)’ token 错误:预期的标识符或'}'令牌}之前的'(' - error: expected identifier or ‘(’ before ‘}’ token } 错误:预期标识符或 '(' 在 '=' 标记之前 - error: expected identifier or '(' before '=' token “'''之前的”预期标识符'或''''''''''''和'''''''''''''''''''''''' - “ expected identifier or ‘(’ before ‘[’ token” and “ error: expected ‘)’ before ‘A’”
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM