LeonelG - 4 months ago 41

C Question

I would like to know if there is any simple way to sum two rows of a 2D array in C without using a loop. I got the following sample code in the main function

`for (i = 0; i < 3; i++) {`

(*A)[i] = drand48();

(*B)[i] = drand48();

}

I'm using two pointers (A and B) to an array of length 3, and after initializing them with random numbers I want to sum them in a single sentence (like a vector sum). Let C be another pointer to an array of length 3. I have tried

`(*C) = (*A) + (*B);`

But I'm getting an error with that. In fortran, one can do it simply by putting:

`C = A + B`

Assuming A, B, and C are arrays of the same length, and both A and B are initilized. Or, if we want to sum two rows of a 2Darray, we can put:

`C = A(i,:) + A(j,:)`

which sum the row i to the row j.

So, there's a analogous way in C??

Thaks for your help.

Answer

There are several things you should understand: First, fortran compiles a loop for you, so when its code runs it is still looping through the data. Second, an optimizer might do some work for you by "un-rolling" the loop. You could write your code that essentially unrolls a small loop, as:

```
for (i = 0; i < 2; i++) {
C[i][0] = A[i][0] + B[i][0];
C[i][1] = A[i][1] + B[i][1];
C[i][2] = A[i][2] + B[i][2];
}
```

However, the **same** number of adds is still executed whether you code in Fortran, Matlab (a vector oriented language) or C (with or without loop unrolling).