C ++ error when using struct variable

I have this structure:

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 structure to be assigned to all 100 elements of the array all[], when I do cout << all[1].nod[30];everything works fine, no errors are output 0. When I call clearMatrix(1), I get this error: error: request for member nod in all[1], which is of non-class type intwhat am I doing wrong ?!

+4
source share
4 answers

A massive variable allis local to the function main, so you cannot refer to it in clearMatrixunless you pass a pointer to it in the function:

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


int main()
{
    noduri all[100];
    clearMatrix(5, all);
    return 0;
}
+6
source

, , ,

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

. . std::vector, , , std::array, , .

++ , (!) , , int double. std::vector std::array, , , .

:

#include <array>
#include <iostream>

struct noduri {
    std::array<int, 100> nod;
};

void clearMatrix(std::array<noduri, 100> const &array) {
    std::cout << array[1].nod[30];
}

int main() {
    std::array<noduri, 100> all;
    std::cout << all[1].nod[30];
}

, std:: array , ++ 11. boost::array std::vector.

+1
source

The code you showed will not compile and does not make any sense. If I understand correctly, you want to assign each element of the array to some value in the clearMatrix function. If so, then the code will look as follows.

#include <iostream>

struct noduri
{
    int nod[100];
};

int clearMatrix( noduri *matrix, int size, int var )
{
   for ( int i = 0; i < size; i++ )
   {
      for ( int &n : matrix[i].nod ) n = var;
   }
}

int main()
{
    const int N = 100;   
    noduri all[N] = {};

    std::cout << all[1].nod[30] << std::endl;

    clearMatrix( all, N, 10 );

    std::cout << all[1].nod[30] << std::endl;

    return 0;
}
0
source

Source: https://habr.com/ru/post/1534027/


All Articles