c - C 函数示例

标签 c function vector

我刚开始学习 C 语言的函数,这让我停了下来。我想编写一个函数来搜索 SIZE 元素 vector 中的元素。这是代码:

#include <stdio.h>
#define SIZE 10

int find(int vet[], int SIZE, int elem);

int main()
{
    int vett[SIZE] = {1, 59, 16, 0, 7, 32, 78, 90, 83, 14};
    int elem;

    printf ("Imput the element to find: ");
    scanf  ("%d", &elem);

    find(vett[SIZE], SIZE, elem);

    if (find == 1)
        printf ("\nI find the element!");
    else if (find == 2)
        printf ("\nI did not find the element!");

    return 0;
}

int find(int vett[], int SIZE, int elem)
{
    int i;
    int flag = 0;

    for (i = 0; i < SIZE; i++)
        if (vett[i] == elem)
            flag = 1;

    if (flag == 1)
        return 1;
    else
        return 2;
}

为什么 Code::Blocks 对我说:

|4|error: expected ';', ',' or ')' before numeric constant| 
||In function 'main':| |8|error: expected ']' before ';' token| 
|14|error: 'vett' undeclared (first use in this function)| 
|14|error: (Each undeclared identifier is reported only once| 
|14|error: for each function it appears in.)| 
|14|error: expected ']' before ';' token|
|14|error: expected ')' before ';' token| 
|16|warning: comparison between pointer and integer|

|18|warning: comparison between pointer and integer|
|24|error: expected ';', ',' or ')' before numeric constant|
||=== Build finished: 8 errors, 2 warnings ===|

我做错了什么?

最佳答案

您正在使用 preprocessor在你不应该去的地方;让我解释一下。

你的线路

#define SIZE 10

告诉编译器所有出现的 4 个字母“SIZE”都将替换为“10”。

您的代码将如下所示:

int find(int vet[], int SIZE, int elem); // before preprocessor
int find(int vet[], int 10, int elem);   // after preprocessor -> syntax error

第二行在 C 中无效。

您应该做的是尽量不要将预处理器定义用作变量名。 例如,我所做的是:我用 CAPS 命名我的预处理器宏(你这样做了)并且总是只用 CamelCasesmallletters 命名我的函数变量em>.

编辑:我的建议:

int find(int vett[], int size, int elem);

int find(int vett[], int size, int elem)
{
    int i;
    int flag = 0;

    for (i = 0; i < size; i++)
        if (vett[i] == elem)
            flag = 1;

    if (flag == 1)
        return 1;
    else
        return 2;
}

关于c - C 函数示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10793835/

相关文章:

c - scons:警告:不推荐调用缺少的 SConscript 而不会出现错误

c - 在 int 和 double 之间进行运算

c++ - 为什么按值传递而不是按常量引用传递?

c++ - 使用带有 vector 的静态字符串

python - 解码勒索信(从 C 到 Python)

c - 以下代码有什么问题?

r - 获取一式三份记录的 rowSums 并仅保留具有最高值的记录

c++ - 创建和调用空函数

c++ - 如何删除或清除结构数据类型的 vector

java - std::vector 使用 swig 生成 java.util.Vector 代码