appending data dynamically in as few loops as possible
===

I have a matrix `A=(n,m)` and I need to scan its columns one by one and if the sum of the elements of a column is greater than a threshold, put the column into a new matrix `B=(n,?)`.

Obviously, i do not know how many columns in `B`, therefore in a first loop, I check the sum of elements in a column, then if the value is greater than the threshold I repeat the loop for appending the column in `B` by a `realloc`.

    okcol=0;
    double *B = malloc(n*sizeof(double));
    for (col=0;col<m;col++){
      sum=0;
      for (row=0;row<n;row++){
        sum+=A[row+col*n];
        if(sum>threshold){
          B = realloc(B, (okcol+1)*n*sizeof(double));
          for (row2=0;row2<n;row2++){
            B [okcol*n+row2] = A[row2+col*n];
          }
          okcol++;
        }  
      }          

Is there a method for automatically append the elements in `B` and "delete" them if the sum is less than threshold? In other words I would like to avoid the last loop.



