简体   繁体   中英

Assign value to the first m elements of an array of size n in C++

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

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM