0

i dont know whats wrong with my code but im getting same value of "sum" on the screen.. assume that m and n are entered equal ....enter image description here

#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((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;
}

}
  • 1
    `malloc.h` is deprecated. Just so you know. – StoryTeller - Unslander Monica Jun 22 '17 at 08:33
  • 1
    Don't use malloc or C-style arrays in C++. `malloc h` is non-standard. Get a [book on C++](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). – n. m. could be an AI Jun 22 '17 at 08:39
  • Use indexing instead of pointer arithmetic and you'll see it. (`*p` is equivalent to `p[0]`. ) – molbdnilo Jun 22 '17 at 08:42
  • What do you want in the case when m! =n? Also replace *(sum+j) = (*(ptr1+j) + *(ptr2+j)) ; – Pushan Gupta Jun 22 '17 at 08:43
  • Also its strange your loop runs only 2 times when n and m are 3 – Pushan Gupta Jun 22 '17 at 08:46
  • 1
    Don't use `malloc` & `free` but at least `new` & `delete`, but prefer [smart pointers](http://en.cppreference.com/w/cpp/memory) – Basile Starynkevitch Jun 22 '17 at 08:53
  • 2
    Also, use [standard containers](http://en.cppreference.com/w/cpp/container) when possible – Basile Starynkevitch Jun 22 '17 at 09:02
  • @BasileStarynkevitch or if you *insist* on using malloc then use free... – doctorlove Jun 22 '17 at 09:23
  • 1
    Your image of text [isn't very helpful](//meta.unix.stackexchange.com/q/4086). It can't be read aloud or copied into an editor, and it doesn't index very well, meaning that other users with the same problem are less likely to find the answer here. Please [edit] your post to incorporate the relevant text directly (preferably using copy+paste to avoid transcription errors). – Toby Speight Jun 22 '17 at 09:30
  • 1
    Please [edit] your code to reduce it to a [mcve] of your problem. Your current code includes much that is peripheral to your problem - a minimal sample normally looks similar to a good unit test: only performing one task, with input values specified for reproducibility. – Toby Speight Jun 22 '17 at 09:31

2 Answers2

2

First, the reason you get the same number springs from where you form the sums. In this loop

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

you find the sum of the contents of ptr1 and ptr2 over and over which never change - this is always the first two numbers.

So, we could iterate over the arrays by indexing in j along as follows

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

BUT what happens if m!=n? You'll walk off the end of the array.

If you change the loop to

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

then you find the sum for pairs of numbers up to the smaller of m and n. You will have to do likewise with the display of the results

for (int j = 0; j<m && j<n; j++)
{
    cout << *(sum + j) << endl;
}

However, I believe you wanted to either display n numbers, regardless of which is bigger, or perhaps assume a 0 if there is no element. Also, I notice you have malloced and not freed - perhaps using a C++ array rather than C-style arrays is better? I'll come to that in a moment.

Let's do the C appraoch and have a 0 if we go beyond the end of an array. This will work, but can be tidied up - comments inline about some important things

#include<stdlib.h>
#include <algorithm> //for std::max
#include <iostream>

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((std::max(n, m)) * sizeof(int)); 
    //                     ^--- sum big enough for biggest "array"
    // data entry as before - omitted for brevity    

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

    cout << " the sum is " << endl;
    for (int j = 0; std::max(n, m); j++)//however big it is
    {
        cout << *(sum + j) << endl;
    }
    free(ptr1); //tidy up
    free(ptr2);
    free(sum);
}

I know you said you wanted to use malloc and perhaps this is a practise with pointers, but consider using C++ idioms (at least you won't forget to free things you have maoolced this way).

Let's nudge your code towards using a std::vector: First the include and the input:

#include <algorithm>
#include <iostream>
#include <vector>

using namespace std;
int main()
{
    int n, m;
    vector<int> data1, data2, sum;
    cout << " enter the size of 1st and 2nd array : " << endl;
    cin >> n >> m;

    cout << "enter 1st array element :";
    for (int i = 0; i<n; i++)
    {
        int number;
        cin >> number;
        data1.push_back(number); //there is a neater way, but start simple
    }

    cout << "enter 2st array element :";
    for (int i = 0; i<m; i++)
    {
        int number;
        cin >> number;
        data2.push_back(number);
    }

This post shows a way to neaten up the data entry. However, let's do something simple and get the sum:

    for (int j = 0; j < std::max(m, n); j++)
    {
        int number = 0;
        if (j < n)
            number += data1[j];
        if (j < m)
            number += data2[j];
        sum.push_back(number);
    }

And now for a C++ way to do output

    cout << " the sum is " << endl;
    for (auto item : sum)
    {
        cout << item << '\n';
    }
}

Finally, let's have a brief think about the sum.

If you now #include <iterator> you can use an algorithm to put your sum into sum

std::transform(data1.begin(), data1.end(),
    data2.begin(), std::back_inserter(sum), std::plus<int>());

However, note this won't fill with zeros. You could either make the vectors the same size, filled with zeros first, or lookup/discover ways to zip vectors of different sizes. Or stick with ifs in a loop as I demonstrated above.

Avoid malloc in C++. Just saying.

doctorlove
  • 18,872
  • 2
  • 46
  • 62
1

I highly encourage you to use a modern cpp data structure like a vector for storing your data. Thus, you don't have to worry about malloc and can access them far more easyly.

But now to your question: Your summation for loop is broken. Use

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

Best regrads, Georg

schorsch312
  • 5,553
  • 5
  • 28
  • 57