Click here to Skip to main content
14,735,205 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi.. Can someone please tell me what's the wrong with this code ?

int getSum(int*, int, int);

void main(void)
{
	int myArray[2][5]{{ 10, 10, 10, 10, 10 }, { 2, 2, 2, 2, 2 }};
	cout << getSum(*myArray, 2, 5) << endl;
}

int getSum(int* arr, int firstLength, int seconLength)
{
	int sum{};

	for (int i{}; i < firstLength; i++)
		for (int j{}; j < seconLength; j++)
			sum += *((arr+i)+j);
	return sum;
}


All I want to do is get the summary of this two dimensional array using pointers.. But this function returns 92 even if the correct answer is 60.

And please just don't say to use arr[i][j] expression.. I want to do this with pointers..
Thanks in advance !
Posted
Comments
chandanadhikari 20-May-14 10:36am
   
People at CP would love to help but why not debug and find it out yourself ?
Sergey Alexandrovich Kryukov 20-May-14 11:00am
   
Debug what? Why do you think this code could compile? :-)
—SA
M­­ar­­­­k 20-May-14 10:41am
   
It debugs without any errors.. So how am I suppose to find the mistake ? o_O
Legor 21-May-14 3:37am
   
Why do you think your code is wrong?

Well, think about what you are doing.
A 3 x 2 array would be indexed as:
0,0   0,1   0,2
1,0   1,1   1,2
and as a single contiguous block memory would be:
 0     1     2     3     4     5
0,0   0,1   0,2   1,0   1,1   1,2

So when you use the indexes to add to the block start address, you can't just add the indexes together:
sum += *((arr+i)+j);
because that will never access the last two elements!
Instead, you need to multiply one of the indexes by the number of elements in the row:
sum += *(arr + (i * 3) + j);
(For your array, it won't be "3" by the way - but I'm very confident you can work out what it should be!)
   
Comments
Richard MacCutchan 20-May-14 11:08am
   
I hope your confidence isn't misplaced :)
M­­ar­­­­k 20-May-14 11:18am
   
Of course the confidence is misplaced :/ I still don't get that.
Richard MacCutchan 20-May-14 11:21am
   
I don't think he could have made it any clearer. And Griff is well known round here for the clarity of his answers.
OriginalGriff 20-May-14 11:29am
   
:laugh:
What don't you understand?
M­­ar­­­­k 20-May-14 11:45am
   
How the "*(arr + (i * 3) + j);" retrieve the elements of the second dimension..
OriginalGriff 20-May-14 11:53am
   
well, arr is the address of the first element, yes?
and each row has 3 elements, yes?
So the address of the first element of the first row is arr + 0
And the address of the first element of the second row is arr + 3
And the address of the first element of the third row would be arr + 6
And so on: the address of the first element of row "n" will be arr + (n * 3)
(Bear in mind that all sensible languages are zero based, not one)

Also the address of the second element of the first row is arr + 1
The second element of the second row is (arr + 3) + 1
And so on.

Which means that the address of the "y"th element of the "x"th row is
arr + (x * 3) + y

Make sense now?
M­­ar­­­­k 20-May-14 12:12pm
   
Thanks.. I didn't know that elements from multidimensional arrays can be retrieved as from single dimensional arrays.. :)
OriginalGriff 20-May-14 12:17pm
   
:laugh: Memory is just one *BIG* single dimensional array in reality: all other storage designs are basically just layers over the top of that!
M­­ar­­­­k 20-May-14 12:35pm
   
It is.. :/ Everything we see are just illusions :/ I thought they are real :/
Some strange syntax in your code; it would not even compile with Microsoft's C compiler. I finally got it to work with the following:
int getSum(int* arr, int firstLength, int seconLength)
{
    int sum = 0;
    
    for (int i = 0; i < firstLength; i++)
        for (int j = 0; j < seconLength; j++)
            sum += *(arr+i*seconLength+j);
    return sum;
}

int main()
{
    int myArray[2][5] = {{ 10, 10, 10, 10, 10 }, { 2, 2, 2, 2, 2 }};
    cout << getSum((int*)myArray, 2, 5) << endl;
    
}
   
Comments
Sergey Alexandrovich Kryukov 20-May-14 11:24am
   
It's actually much simpler than that. :-)
—SA
Richard MacCutchan 20-May-14 11:31am
   
That all depends how you define "simple" :)
Sergey Alexandrovich Kryukov 20-May-14 13:46pm
   
:-)
M­­ar­­­­k 20-May-14 11:42am
   
"sum += *(arr+i*seconLength+j);"

This solved the problem.. Thanks... But I still dont get what part i*seconlength+j takes in this code.

As I understand, in the first round of the first loop and, the first round of the second loop..

arr+i = arr[0] element
arr+i*seconLength = arr[0] element
arr+i*seconLength+j = arr[0] element..

As I see, this line doesn't care about the 2nd dimension of the array..
Can u please explain some further how this retrieve values from the arr[0] and arr[1] array ?

Thanks..
Richard MacCutchan 20-May-14 11:55am
   
First time round when i is 0, i * seconLength = 0 * 5 = 0 so adding j (from 0 to 4) gets you the first 5 elements (0 to 4).
Second time round when i is 1, i * seconLength = 1 * 5 = 5 so adding j (from 0 to 4) gets you the second 5 elements (i.e 5+0, 5+1 ...).
f.sattari 20-May-14 11:58am
   
arr=address for a[0]
if arr[m][n]
address for first element in i row = arr+i*n
and address for element in m,n=arr+i*n+j
M­­ar­­­­k 20-May-14 12:10pm
   
Oh. I got it.. Thanks :) I didn't knew that elements of multi dimensional arrays can be retrieved like from a single dimensional array...
please check this code and you anderstand the your wrong

#include "stdafx.h"
#include <iostream>

using namespace std;


int getSum(int*, int, int);
 
void main(void)
{
	int myArray[2][5]={{ 10, 10, 10, 10, 10 }, { 2, 2, 2, 2, 2 }};
			cout<<"before sent to func"<<endl;
	for (int i=0; i<2;i++)
		for(int j=0;j<5;j++)
		cout<<"myArray["<<i<<"]["<<j<<"]="<<myArray[i][j]<<endl;
	cout <<"SUM="<< getSum(*myArray, 2, 5) << endl;
}
 
int getSum(int* arr, int firstLength, int seconLength)
{
	int sum=0;

 	cout<<"after sent to func"<<endl;
	for (int i=0; i < firstLength; i++)
		for (int j=0; j < seconLength; j++)
		{
			cout<<"myArray["<<i<<"]["<<j<<"]="<<*((arr+i)+j)<<endl;
			sum += *((arr+i)+j);
		}
	return sum;
}



before sent to func

myArray[0][0]=10
myArray[0][1]=10
myArray[0][2]=10
myArray[0][3]=10
myArray[0][4]=10
myArray[1][0]=2
myArray[1][1]=2
myArray[1][2]=2
myArray[1][3]=2
myArray[1][4]=2


the elements to sent SUM

myArray[0][0]=10
myArray[0][1]=10
myArray[0][2]=10
myArray[0][3]=10
myArray[0][4]=10
myArray[1][0]=10
myArray[1][1]=10
myArray[1][2]=10
myArray[1][3]=10
myArray[1][4]=2
SUM=92
   
v2
Comments
M­­ar­­­­k 20-May-14 12:12pm
   
Thanks.. I didn't know that elements from multidimensional arrays can be retrieved as from single dimensional arrays.. :)
You really need to show the code you were dealing with, not anything else. What you show, with all those sum{}, j{} and i{} is just the gibberish which could not compile.

It would be enough to write this:
int getSum(int* arr, int firstLength, int seconLength)
{
	int sum = 0;
	for (int index = 0; index < firstLength * seconLength; ++index)
	   sum += arr[index];
	return sum;
}

Why? Because such multidimensional arrays are actually the single-dimensional ones, please see:
Please see: http://www.cplusplus.com/doc/tutorial/arrays[^].

—SA
   
Comments
M­­ar­­­­k 20-May-14 12:12pm
   
Thanks.. I didn't know that elements from multidimensional arrays can be retrieved as from single dimensional arrays.. :)
Sergey Alexandrovich Kryukov 20-May-14 13:43pm
   
You are welcome. Now you know this simple and fundamental fact.
Good luck, call again.
—SA
Stefan_Lang 21-May-14 2:05am
   
I considered commenting about those {} bits, too. But I did experience some odd residuals in postings due to HTML getting in the way, so I didn't know if that was in the original code at all! It sure looked odd, and as you say it shouldn't compile, so I strongly believe that is not the literal code the author has in front of him.
Stefan_Lang 21-May-14 2:15am
   
P.S.: You're right, this version is really much better. I was considering changing the arr argument to the actual type, but frankly I don't like passing around multidimensional array types - you always end up either with changed dimensionality requirements, or worse, with requirements to use your function for varying array sizes. Your solution avoids that problem altogether!

That said, maybe the sum function really should only take two arguments: the array and the total size. The caller knows the total size after all, and the sum function really doesn't care what the original dimensionality is!
Aescleal 22-May-14 10:03am
   
T t{}; means "t is a T that's default initialised."

It's not gibberish - it's standard C++.
try changing
sum += *((arr+i)+j);

to
sum += *((arr+i*firstLength)+j);
   
Comments
M­­ar­­­­k 20-May-14 10:46am
   
Sorry :/ it returns 84 not the correct summary..
Richard MacCutchan 20-May-14 11:02am
   
i * seconLength is required, to get past the first group of 5. And it took me a few goes to work that out.
Stefan_Lang 21-May-14 2:09am
   
Yeah, somehow I always mix up rows and columns. :-( Next time I should simply point out the reasonable arr[*][*] way rather than fix odd memory pointer arithmetic ;-)
Richard MacCutchan 21-May-14 3:31am
   
Me too, but OriginalGriff's pictures and explanation make it all nice and clear.
M­­ar­­­­k 20-May-14 12:12pm
   
Thanks.. I didn't know that elements from multidimensional arrays can be retrieved as from single dimensional arrays.. :)
Sergey Alexandrovich Kryukov 20-May-14 13:45pm
   
The solution is way simpler than that... :-)
—SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900