C语言中的函数示例

时间:2012-05-29 06:04:28

标签: c function vector

我刚开始研究C中的函数,这阻止了我。我想编写一个函数来搜索SIZE元素向量中的元素。这是代码:

#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 ===|

我做错了什么?

3 个答案:

答案 0 :(得分:6)

您在不应该使用的地方使用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(你做过)命名我的预处理器宏,总是 CamelCase smallletters命名我的函数变量

编辑:我的建议:

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

答案 1 :(得分:3)

如果您使用SIZE作为常量,那么您不需要将其传递给函数:

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

如果您希望该函数是通用的,然后像这样定义它的原型:

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

并将其称为:

find(vett, SIZE, 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;
}

== EDIT == 关于评论中的问题:
find是指向函数的指针,它不保存返回值。您可以通过以下方式之一使用它: -1 -

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

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

-2 -

if (find(vett[size], size, elem) == 1)
    printf ("\nI find the element!");
else if (find == 2)
    printf ("\nI did not find the element!");

答案 2 :(得分:2)

你传递的不是整个矢量vett,而是它的SIZE-th元素传递给函数find()。