homegrown
homegrown

Reputation: 187

Dynamically allocated array in C++

I am playing around with dynamically allocating an array in c++. I have this code

#include <iosteam>
using namespace std;

void A(int* arr)
{
    for(int i = 0; i < 10; i++)
        cout << arr[i] << endl;
}

int main()
{
    int **nums;
    nums = new int*[10];
    for(int i = 0; i < 10; i++)
        nums[i] = new int(i);

    for(int i = 0; i < 10; i++)
        cout << *nums[i] << endl;

    cout << endl;
    A(*nums);
    return 0;
}

This gives me the output

0
1
2
3
4
5
6
7
8
9

0
0
0
0
0
0
33
0
1
0

My question is: When the array is passed to the function A(int* arr), why does the array printed there have different output than what the array defined in main() has? I have been studying dynamic allocation and double pointers, but I can't seem to figure this one out. I have searched through SO questions and can't find a suitable answer to this question. I would like to know if I can print the values of the array in the function A(), or if it is even possible to do it this way. Any help is appreciated.

Upvotes: 1

Views: 214

Answers (2)

zh01085105
zh01085105

Reputation: 21

the answers above is quite right and you can modify your code as follows.

void A(int** arr)

{

    for(int i = 0; i < 10; i++)
       // cout << *arr[i] << endl; or bellow
        cout <<arr[i][0]<<endl;
}

reference in your main as "A(nums)";

Upvotes: 2

R Sahu
R Sahu

Reputation: 206567

Your function:

void A(int* arr)
{
    for(int i = 0; i < 10; i++)
        cout << arr[i] << endl;
}

is getting called with A(*nums).

You are effectively executing:

for(int i = 0; i < 10; i++)
        cout << (*nums)[i] << endl;

which is equivalent to:

for(int i = 0; i < 10; i++)
        cout << nums[0][i] << endl;

You are seeing the effects of undefined behavior since you are accessing unauthorized memory.

Remember that you only have access to

num[0][0]
num[1][0]

....

num[9][0]

and not

num[0][0]
num[0][1]

....

num[0][9]

Upvotes: 5

Related Questions