How to add two arrays of integers with pointer arithmetic?

Asked

Viewed 3,467 times

7

I am doing an exercise where I pass by parameter two integer arrays already defined by the user. I need now, in a third array, to store the sum of the two received arrays, at 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 receive 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;
}
  • 1

    Be more specific in your question. What did you try to do? What didn’t work out?

  • 1

    I downvoted because your question does not show any effort. Show your code, say what you tried, what you did not know how to do, etc.

  • Okay, I’ve passed the user-filled vectors 1 and 2, he chooses the size of vectors 1 and 2 and fills them in. My main doubt is how I should receive the sum of these vectors using pointer arithmetic, I cannot run them with loop and sum them, it has q be with pointer arithmetic. Follow my function int soma_pointer(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; }

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]);
  • Guy ball show, need to abstract even, with the loop so was perfect.

0

To be able to perform operations between two vectors in a function you have to comply with these "rules":

  1. Pass vectors by parameter
  2. Pass vector size by parameter

After that just go through the vector in a cycle, you can use a counter i, and use the pointer-less array in this way: vector[i] = 1 + 2; or else *(vector + i) = 1 + 2

Browser other questions tagged

You are not signed in. Login or sign up in order to post.