adding two arrays using dynamic memory allocation

What's the problem with my code ...
i am getting same value of sum in the loop.
assumed m and n are equal i know theres logical error but assume they are same .
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include<stdio.h>
#include<malloc.h>
#include<iostream>
#include<stdlib.h>
using namespace std;
int main()
{
    int n,m;
    int *ptr1, *ptr2, *sum;
    cout<<" enter the size of 1st and 2nd array : "<<endl;
    cin>>n>>m;
    ptr1=(int*)malloc(n*sizeof(int));
    ptr2=(int*)malloc(m*sizeof(int));
    sum=(int*)malloc((m+n)*sizeof(int));

    cout<<"enter 1st array element :";
    for(int i=0;i<n;i++)
    {
        cin>>*(ptr1+i) ;
    }

    cout<<"enter 2st array element :";
    for(int i=0;i<m;i++)
    {
        cin>>*(ptr2+i);
    }

    for(int j=0;j<m||j<n;j++)
    {
        *(sum+j) =  (*(ptr1) +  *(ptr2)) ;
    }

    cout<<" the sum is "<<endl;
    for(int j=0;j<m||j<n;j++)
    {
        cout<<*(sum+j)<<endl;
    }

}
Last edited on
You've forgot to add the indices to ptr1 and ptr2 when calculating the sum.
omg pardon me its unbelievable how stupid i could be :/
Is there a reason why you use pointer arithmetic syntax?

This line
 
*(sum+j) = (*(ptr1+j) + *(ptr2+j)) ;
could be written as
 
sum[j] = ptr1[j] + ptr2[j];
which is much more readable in my opinion.
because i am practicing pointers....
Topic archived. No new replies allowed.