title: Sum of elements in a matrix using threads in c
body: <p>The problem statement goes like this: Calculate the sum of the elements in a bidimensional matrix, using a <em>separate thread</em> to calculate the sum of <strong><em>each row</em></strong>. The main thread adds up these sums printing the final result.</p>
  
  <p>From what I have seen so far, the code runs correctly. The only issue is when I choose the number of rows to be <em>smaller</em> than the number of columns (e.g. rows = 2, columns = 3), because it only computes the sum for the first 2 columns, completely ignoring the third one.</p>
  
  <p>This is the code I wrote in C and I would really appreciate any help understanding what I did wrong or missed. Thank you.</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;pthread.h&gt;
  
  #define M 10
  #define N 10
  
  int rows, columns, a[M][N], s[M];
  
  // compute the sum of each row
  
  void* f(void* p) {
     int k = *((int*) p);
     int i;
     for (i = 0; i &lt; columns; i++) {
        s[i] += a[k][i];
     }
     return NULL;
  }
  
  int main() {
      int i, j, *p, rc;
      int sum = 0;
      pthread_t th[M];
  
      // matrix creation
      printf("no. of rows = ");
      scanf("%d", &amp;rows);
      printf("no. of columns = ");
      scanf("%d", &amp;columns);
  
      for (i = 0; i &lt; rows; i++) {
          for (j = 0; j &lt; columns; j++) {
              printf("a[%d][%d] = \n", i, j);
              scanf("%d", &amp;a[i][j]);
          }
      }
  
      printf("\nThe matrix is: \n");
      for(i=0; i &lt; rows; i++) {
          for(j=0; j &lt; columns; j++)
              printf("%d ", a[i][j]);
      printf("\n");
      }
  
      // thread creation
      for (i=0; i &lt; rows; i++) {
          p = malloc(sizeof(int));
          *p = i;
          rc = pthread_create(&amp;th[i], NULL, f, p);
          if (rc != 0) {
              printf("Thread creation failed");
              exit(-1);
          }
      }
  
      for (i=0; i &lt; rows; i++) {
          pthread_join(th[i], NULL);
      }
      // compute the final sum
      for (i=0; i &lt; rows; i++) {
          sum += s[i];
      }
      printf("The sum is = %d\n", sum);
  
      return 0;
      }
  </code></pre>