1

此代码在 C 中是否合法?我收到 & 符号错误。我正在使用适用于 Ubuntu 的 Eclipse C/C++ IDE 来简化此过程。

void is_done(int &flag , char* ptr)
{
    int i=0;
    for(i=0;i<3;i++)
    {
        if(*ptr[i][0]==*ptr[i][1]==*ptr[i][2]||*ptr[0][i]==*ptr[1][i]==*ptr[2][i])
        {
            flag=1;
            return;
        }
    }
    if(*ptr[0][0]==*ptr[1][1]==*ptr[2][2]||*ptr[0][2]==*ptr[1][1]==*ptr[2][0])
    {
        flag=1;
        return;
    }
}

GCC 给我一个错误:

expected ‘;’, ‘,’ or ‘)’ before ‘&amp;’ token
ipttt.c /OS line 7  C/C++ Problem

我真的不明白这个错误。

4

4 回答 4

4

C 没有引用。您的代码是 C++。在 C 中,您必须使用指针:

void is_done(int *flag , char* ptr)
{
    ...
    *flag = 1;
    ...
}
于 2013-02-18T13:57:39.767 回答
2

C 中没有“按引用传递”:那是 C++。C 中唯一可用的选项是通过指针传递

void is_done(int *flag , char* ptr)
{
    ...
    *flag=1;
    ...
}

您还需要&&使用这些链==:它们可以编译,但它们不会执行您希望它们执行的操作:

// DOES NOT WORK !!!
if(*ptr[0][0]==*ptr[1][1]==*ptr[2][2]||*ptr[0][2]==*ptr[1][1]==*ptr[2][0])

你需要这个:

if((*ptr[0][0]==*ptr[1][1] && *ptr[0][0]==*ptr[2][2]) || (*ptr[0][2]==*ptr[1][1] && *ptr[0][2]==*ptr[2][0])) {
    ...
}
于 2013-02-18T13:57:51.260 回答
1

&在声明中使用字符的引用是 C++ 的事情。要将“对象”作为 C 中的引用传递,您必须使用指针:

void is_done(int *flag , char* ptr)
{
    ...

    *flag = 1;

    ...
}
于 2013-02-18T13:59:21.217 回答
1

你想要的是像这样传递一个指向 int 的指针:

void is_done(int *flag , char* ptr)
{
            // Then you must deference the variable to set the value
    *flag = 1; // or whatever value you want

然后你会用这样的标志调用你的函数:

int main()
{
   int flag = 0;
   char * ptr = NULL;
   ...
   is_done(&flag, ptr);  // Note that's not "reference" here, that's the address of
                         // your local flag variable

当然,您可以只使用指针,但由于您试图“通过引用传递”,我假设您一开始并没有在代码中使用指针。

于 2013-02-18T14:01:49.997 回答