Reputation: 35
I have an array declared in the global scope (outside the main()
function) of size n
, and inside the main()
I need to assign it the first m
(m < n
) values. How do I approach this?
#include <iostream>
using namespace std;
int array[50];
int main()
{
array = {1,2,3,4,5}; //can not execute, error
return 0;
}
The error I am getting:
assigning to an array from an initializer list
Upvotes: 3
Views: 896
Reputation: 341
If you are trying to initialize the array with some initial values, you have to do this immediately with the initialization, not after the initialization.
#include <iostream>
using namespace std;
int main(){
int array[50] = {1,2,3,4,5};
return 0;
}
But, if you really need to copy values, the easiest way is to copy values one by one.
#include <iostream>
using namespace std;
int array[50];
int main(){
int temp[5] = {1,2,3,4,5};
for (int i = 0; i < 5; i++)
array[i] = temp[i];
return 0;
}
Upvotes: 5