Declare an array in Global but initialization in function

Nov 1, 2019 at 1:58pm
Hello,
I want to declare an array in Global but initialization in function.
How can I initialization array in a method without pointer?



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

int b[5];

void main()
{
	{

		b = {1,2,3,4,5}; //error

	}
}
Last edited on Nov 1, 2019 at 2:04pm
Nov 1, 2019 at 2:02pm
void main is a nonstandard extension. main should be of type int in c++.
most people say method for a member function. you do not have a class (or struct). You may be wanting a free-floating function?
1
2
3
4
5
6
7
8
9
10
void init_b()
{
   for(int dx = 0, i = 1; i < 6; i++)
      b[dx++] = i;
}

int main()
{
    init_b();
}


globals are nothing but trouble. I highly recommend you find a better way: at the very least wrap them in a class as a static variable (and then you could have the init tied to it, as a bonus).

vectors support = assignment operator. C-Arrays do not, except upon creation.
why not just say
int b[] = {1,2,3,4,5}; and save writing a function?
Last edited on Nov 1, 2019 at 2:06pm
Topic archived. No new replies allowed.