0

I m using recursive technique to display 2d array, I am treating 2d array as 1 d array but giving me output like address. Please tell me what to do.

void data(int i,int arr[2][2],int size){
if(i<4){

    if(i%2==0){
        cout<<endl;
    }
    cout<<arr[i]<<" ";
    data(i+1,arr, size);

}
5
  • 2
    How exactly is this recursive??? You aren't exactly calling your "data" routine from within your "data" routine. Commented Feb 15, 2014 at 18:57
  • @trumpetlicks it is. The function is calling itself. Commented Feb 15, 2014 at 18:58
  • What is your question? Why did you tag it C if it's C++? Commented Feb 15, 2014 at 18:59
  • @IvayloStrandjev - He must have edited the original question, originally he was calling another function "display" NOT "data". Commented Feb 15, 2014 at 19:00
  • Yep, I confirm what @trumpetlicks is saying Commented Feb 15, 2014 at 19:01

2 Answers 2

1

If you want to treat this as a 1d array, you must declare it as so:

void data(int i,int arr[],int size) {

Or:

void data(int i,int *arr,int size) {

The reason is that otherwise, arr[i] is interpreted as an array of 2 integers, which decays into a pointer to the first element (and that's the address that is printed).

Declaring it as a 1-dimensional array will make sure that arr[i] is seen as an int.

Note that whoever calls this function cannot pass a 2D array anymore, or, put another way, cannot make that obvious to the compiler. Instead, you have to pass it a pointer to the first element, as in:

data(0, &arr[0][0], 4);

Or, equivalently:

data(0, arr[0], 4);

This just affects the first call, the recursive call is correct, of course.

In other words, the code should work, you just need to change the declaration of the parameter arr

Sign up to request clarification or add additional context in comments.

Comments

0

You can not print array like this

 cout<<arr[i]<<" ";

This will gives you address of first element

If you want to print all elements of array, you need to use loop

for (int j = 0; j < 2; j++)  cout<<arr[i][j]<<" ";

3 Comments

I want it recursively
He said he wants to treat it as a 1D array.
Dont use recursion for problems like this. Its overkill.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.