How to sum two integer arrays with pointer arithmetic?

7

I'm doing an exercise in which I pass by parameter two arrays of integers already defined by the user. I need now, in a third array, to store the sum of the two received arrays, in the same positions, using pointer arithmetic.

Ex:

vet 1 [1,2,3]
vet 2 [1,2,3] 

Here in the third vector I have to get the sum using pointer arithmetic.

vet 3 [2,4,6]

My attempt:

#include <stdio.h>
#define MAX 100
int soma_ponteiro(int *vet1,int *vet2,int num);
int main(){

    int vet1[MAX],vet2[MAX];
    int num,i;

    printf("Digite qtd de numeros:\n");
    scanf("%d",&num);

    for(i=0;i<num;i++){
        printf("\nDigite numero %d vetor 1\n",i+1);
        scanf("%d",&vet1[i]);
        printf("\nDigite numero %d vetor 2\n",i+1);
        scanf("%d",&vet2[i]);
    }

    soma_ponteiro(vet1,vet2,num);
    printf("\n%d",soma_ponteiro(vet1,vet2,num));

    return 0;
}
int soma_ponteiro(int *vet1,int *vet2,int num){
    int vet3[MAX];
    int *last_pos=vet1+num;
    int *ptr = vet1;
    int *ptr2= vet2;
    int *ptr3= vet3;

    while(ptr<last_pos){
        *ptr3 = *vet1+*vet2;
    ptr++;
    }
    return ptr3;
}
    
asked by anonymous 12.02.2014 / 21:01

2 answers

5

See if this is what you want:

int vet1[3]={1, 2, 3}, vet2[3]={1, 2, 3}, vet3[3], *p1, *p2, *p3, i;
p1 = vet1;
p2 = vet2;
p3 = vet3;
for (i=0; i<3; i++) {
    *p3 = *p1 + *p2;
    p1++;
    p2++;
    p3++;
}
for (i=0; i<3;i++)
    printf("\tvet3[%d] = %d", i, vet3[i]);
    
12.02.2014 / 21:14
0

In order to do operations between two vectors in a function, you have to follow these "rules":

  • Passing the vectors by parameter
  • Pass the dimension of the vectors per parameter
  • After that, just cycle through the vector, you can use a i counter, and use the array without pointers, like this: vector[i] = 1 + 2; or *(vector + i) = 1 + 2

        
    08.03.2014 / 15:04