Arrays

I have created a program of arrays to assign value of one array to another array.

This code worked


#include <iostream>

using namespace std;

int main()
{
int arr[]={10,20,30,40,50};
int arr1[]={};

arr1[0]=arr[1];

cout<<arr1[0];



return 0;
}



but the code below did not work.

#include <iostream>

using namespace std;

int main()
{
int arr[]={10,20,30,40,50};
int arr1[];

arr1[0]=arr[1];

cout<<arr1[0];



return 0;
}

can anybody explain why the second code did not work??
I am finding hard to believe your first code worked:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
using namespace std;

int main()
{
    int arr[] = { 10, 20, 30, 40, 50 };
    int arr1[] = {}; // ERROR: An empty initializer is invalid for an
				// array with unspecified bound.

    arr1[0] = arr[1];

    cout << arr1[0];


    return 0;
}


On line 7, you need to allocate the array (i.e. int arr1[5]).

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>

int main()
{
    int arr[] = { 10, 20, 30, 40, 50 };
    int arr1[5]; // Allocate 5 elements in arr1.

    arr1[0] = arr[1];

    std::cout << arr1[0] << std::endl; // It should display 20.

    return 0;
}
Topic archived. No new replies allowed.