Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ error when using struct variable

Tags:

c++

struct

I have this struct:

struct noduri {
    int nod[100];
};

and this function:

int clearMatrix(int var)
{
    cout << all[1].nod[30];
}

int main()
{
    noduri all[100];
    cout << all[1].nod[30];
    return 0;
}

and I want the struct to be assigned to all 100 elements of array all[], when I do cout << all[1].nod[30]; everything works fine, no errors, it outputs 0. When I call clearMatrix(1) I get this error : error: request for member nod in all[1], which is of non-class type int, what am I doing wrong ?!

like image 305
southpaw93 Avatar asked Dec 20 '22 16:12

southpaw93


2 Answers

The array variable all is local to the main function, so you cannot reference it in clearMatrix unless you pass a pointer to it into the function:

int clearMatrix(int var, noduri *all)
{
    cout<<all[1].nod[30];
}


int main()
{
    noduri all[100];
    clearMatrix(5, all);
    return 0;
}
like image 152
Sergey Kalinichenko Avatar answered Jan 02 '23 05:01

Sergey Kalinichenko


you are reffering in the function that array which is not in its scope, you need to do it as

int clearMatrix(int var,noduri *all)
 {
   cout<<all[1].nod[30]; // as here you have the base address of the array of type noduri you can refer it.
 }
 int main()
 {
noduri all[100];
clearMatrix(5, all);
return 0;
}
like image 44
OldSchool Avatar answered Jan 02 '23 05:01

OldSchool