# countnonzero seg fault

Hello , I want to use countNonZero , but I am getting a seg fault at the countNnZero line.

vector<Mat> mycompare;
int compareSize = (N / 2) * (N -1);
mycompare.resize( compareSize );

int myCounts [ compareSize ];

int index = 0;
for ( int idx = 0; idx < N; idx++ )
{
for ( int k = idx + 1; k < N; k ++ )
{
mycompare[ index++ ] = ( A[ idx ] == A[ k ] );
myCounts[ index++ ] = countNonZero( mycompare[ index ] );
}
}


OR

Is there a way to use if statement?:

if ( mycompare[ index ] == 255 )
count++;

edit retag close merge delete

@LorenaGdL:But , I am setting the mycompare , access it in the countNonZero function ,then at the 2nd loop , set the mycompare , access it and so on. ( I am just asking for the if statement )

No. The increment of index does not take place at each loop run, but just after it finishes its sentence. Check the printed values for this code:

for ( int k = idx + 1; k < N; k ++ )
{
cout << "Index: " << index << endl;
mycompare[ index++ ] = ( A[ idx ] == A[ k ] );
cout << "Index: " << index << endl;
myCounts[ index++ ] = countNonZero( mycompare[ index ] );
}


If I'm not wrong, you'll have Index: 0 and Index: 1, showing than in the same loop run you're trying to access two different indexes

Sort by » oldest newest most voted

You're incrementing the index variable twice before using it in mycompare[index]. So, for the first run of the loop, you first set mycompare to some binary matrix, and then you try to set the value of myCounts to the number of non-zero elements of mycompare. And yep, mycompare is still an invalid matrix. Use this:

for ( int k = idx + 1; k < N; k ++ )
{
mycompare[ index ] = ( A[ idx ] == A[ k ] );
myCounts[ index ] = countNonZero( mycompare[ index ] );
index++;
}

more

@LorenaGdL:Yes!You are right,I missed that!Is there a way to use if statement for this? ( please make it an answer if you want)Thanks!

1

@LorenaGdL:If I just do mycompare[ index++ ] = ( A[ idx ] == A[ k ] ); myCounts[ index ] = countNonZero( mycompare[ index ] ); , should't work also ? ( because it doesn't)

No, it shouldn't, because you're setting first matrix in the vector, but trying later to access second matrix. Just put the index++ at the end. And about the if statement, why would you want to use it? Your current code is nice, avoiding per-pixel loops

What about mycompare[ index ] = ( A[ idx ] == A[ k ] ); myCounts[ index ] = countNonZero( mycompare[ index++ ] );?

@thdrksdfthmn that will work too, as the index is incremented on the last operation. I do however prefer to increment variables outside functions, because if I later add another line of code, I migh forget to change that increment too. But I guess that's a matter of personal taste

Official site

GitHub

Wiki

Documentation