Reputation: 322
Is this code legal in C? I'm getting an error for the & sign. I am using Eclipse C/C++ IDE for Ubuntu to make this process easier.
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 gives me an error:
expected ‘;’, ‘,’ or ‘)’ before ‘&’ token
ipttt.c /OS line 7 C/C++ Problem
I really don't understand this error.
Upvotes: 1
Views: 723
Reputation: 49403
What you wanted was to pass a pointer to an int like this:
void is_done(int *flag , char* ptr)
{
// Then you must deference the variable to set the value
*flag = 1; // or whatever value you want
Then you'd call your function with the flag like this:
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
Of course you could just use a pointer, but since you were trying to "pass by reference" I assume you were not using a pointer in your code to begin with.
Upvotes: 1
Reputation: 409176
References using the &
character in declarations is a C++ thing. To pass "objects" as a reference in C you have to use pointers:
void is_done(int *flag , char* ptr)
{
...
*flag = 1;
...
}
Upvotes: 1
Reputation: 726599
There is no "pass by reference" in C: that's C++. The only option available in C to accomplish this is passing by pointer
void is_done(int *flag , char* ptr)
{
...
*flag=1;
...
}
You also need &&
with these chains of ==
: they compile, but they do not do what you want them to do:
// DOES NOT WORK !!!
if(*ptr[0][0]==*ptr[1][1]==*ptr[2][2]||*ptr[0][2]==*ptr[1][1]==*ptr[2][0])
You need this:
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])) {
...
}
Upvotes: 2
Reputation: 14159
C doesn't have references. Your code is C++. In C, you have to use pointers:
void is_done(int *flag , char* ptr)
{
...
*flag = 1;
...
}
Upvotes: 4