Sarah
Sarah

Reputation: 125

Adding two arrays using pointers

I want to add two arrays. Therefore I wrote the following code:

float x[2], y[2];
x[1]=1;
x[2]=2;
y[1]=2;
y[2]=1;
float* end=x+2; // n is the size of the array x
float* p;
float* q; //Given to arrays x and y.


for(p=x,q=y; q,p<end;q++,p++){
        printf("%f",*p+*q );

}

Why does this not work. I only get the first value of new array. Result should be:

3
3

Upvotes: 0

Views: 533

Answers (1)

float x[2], y[2];

x and y are both arrays of 2 elements of type float.

When using x[2] = 2; and y[2] = 1;, you attempt to write the values into a third element (which does not exist) beyond the bounds of the arrays which invokes undefined behavior since subscript indexing starts at 0, not 1.

For the reason why you can take a look at here:

Use:

x[0] = 1;
x[1] = 2;
y[0] = 2;
y[1] = 1;

instead.


Example (Online):

#include <stdio.h>

int main (void)
{
    float x[2], y[2];

    x[0] = 1;
    x[1] = 2;
    y[0] = 2;
    y[1] = 1;

    float* end = x + 2; // n is the size of the array x
    float* p;
    float* q; //Given to arrays x and y.


    for (p = x, q = y ; p < end ; q++, p++) {
        printf("%.2f\n", *p + *q);
    } 
}

Output:

3.00
3.00

Side Notes:

  • "I want to add two arrays."

    Something like that is not possible. In fact, You do not add the arrays; you don't even add certain elements of it. You only add the values of specific elements as argument in the call to printf(). The difference is important.

  • q, in the for loop condition q,p < end has no effect. The expression has the value and type of the right hand operand of the comma operator.

  • Please learn how to format/indent your code properly. It will help you and other readers of your code in the future.

  • Good and free C starting books are Modern C or The C Programming Language (2nd Edition). These and others you can find here:

    The Definitive C Book Guide and List

Upvotes: 2

Related Questions