C++ 初始化全局数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5914992/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C++ Initializing a Global Array
提问by Jimmy Huch
Hey everyone. I am an experienced java programmer and am just learning C++.
嘿大家。我是一名经验丰富的 Java 程序员,正在学习 C++。
Now I have a bit of a beginner's problem. I have an array variable x of type int.
现在我有一个初学者的问题。我有一个 int 类型的数组变量 x。
The user will input the size of x in method B. I want to use x in method A.
用户将在方法B中输入x的大小。我想在方法A中使用x。
void method A()
{
using int x [] blah blah blah
}
void method B()
{
int n;
cin >>n;
int x [n]; // How can I use this int x in method A without getting error: storage size x is unknown.
// Or the error 'x' was not declared in this scope.
}
EDIT: Parameter passing isn't a solution I am looking for.
编辑:参数传递不是我正在寻找的解决方案。
DOUBLE EDIT: I do know about the vector option, but my program is cramming on time. I am creating an algorithm where every millisecond counts.
双重编辑:我知道矢量选项,但我的程序按时填满。我正在创建一个算法,其中每一毫秒都很重要。
BTW I found out a way of doing it.
顺便说一句,我找到了一种方法。
int x [] = {}
method B();
method A () { blah blah use x}
method B () {/*int*/ x [n]}
回答by Brian Roach
If you actually want an array and not a vector, and you want that array dynamically sized at runtime, you would need to create it on the heap (storing it in a pointer), and free it when you're done.
如果您确实想要一个数组而不是一个向量,并且您希望该数组在运行时动态调整大小,则需要在堆上创建它(将它存储在一个指针中),并在完成后释放它。
Coming from Java you need to understand that there's no garbage collection in C++ - anything you new
(create on the heap) in an object you will want to clean up in the destructor with delete
.
来自 Java,您需要了解 C++ 中没有垃圾收集 - 您new
(在堆上创建)在对象中的任何内容都需要在析构函数中使用delete
.
class foo
{
private:
int *array;
public:
foo() { array = NULL; };
~foo()
{
if (array != NULL)
delete [] array;
}
void createArray()
{
array = new int[5];
}
};
More info at: http://www.cplusplus.com/doc/tutorial/dynamic/
回答by Fred Foo
Use a vector:
使用向量:
std::vector<int> x(n);
then pass that to method A as an argument of type std::vector<int> const &
.
然后将其作为 type 的参数传递给方法 A std::vector<int> const &
。
Edit: Or make the vector
a data member of your class and set it with:
编辑:或者使vector
您的类的数据成员并设置它:
size_t n;
std::cin >> n;
x.resize(n);
回答by Mark B
In C++ you can't directly size an array with a runtime value, only with constants.
在 C++ 中,您不能直接使用运行时值来调整数组的大小,只能使用常量。
You almost certainly want vector instead:
你几乎肯定想要向量:
std::vector<int> x(n);
std::vector<int> x(n);
回答by Rob?
EDIT: flesh out answer.
编辑:充实答案。
I can't quite tell if you are trying to learn about arrays, or if you are trying to solve some practical problem. I'll assume the latter.
我不太清楚你是在尝试学习数组,还是在尝试解决一些实际问题。我会假设后者。
The only way for method A to have access to any variable is if it is in scope. Specifically, x
must either be:
方法 A 访问任何变量的唯一方法是它是否在范围内。具体来说,x
必须是:
- a local, including a parameter (but you said no to parameter passing)
- a class member, or
- a global
- 一个本地,包括一个参数(但你对参数传递说不)
- 班级成员,或
- 一个全球性的
Here is a solution in which x
is a class member:
这是一个解决方案,其中x
是一个类成员:
class C {
public:
std::vector<int> x;
void A() {
std::cout << x[2] << "\n"; // using x[], for example.
}
void B() {
int n;
cin >> n;
x = std::vector<int>(n); // or, as others have pointed out, x.resize(n)
}
};
回答by Null Set
This is a version of your example that works in c++.
这是您的示例的一个版本,适用于 C++。
#include <iostream>
int *my_array;
void methodA(a,b){
my_array[a] = b;
}
int methodB(){
int n;
std::cin >> n;
my_array = new int[n];
}
int main(){
int x;
x = methodB();
methodA(x-1, 20);
delete [] my_array;
return 0;
}
回答by Nikki Locke
Be aware that arrays in C++ are much more basic (and dangerous) than in Java.
请注意,C++ 中的数组比 Java 中的更基本(也更危险)。
In Java, every access to an array is checked, to make sure the element number you use is within the array.
在 Java 中,检查对数组的每次访问,以确保您使用的元素编号在数组内。
In C++, an array is just a pointer to an allocated area of memory, and you can use any array index you like (whether within the bounds of the array, or not). If your array index is outside the bounds of the array, you will be accessing (and modifying, if you are assigning to the array element!) whatever happens to be in memory at that point. This may cause an exception (if the memory address is outside the area accessible to your process), or can cause almost anything to happen (alter another variable in your program, alter something in the operating system, format your hard disk, whatever - it is called "undefined behaviour").
在 C++ 中,数组只是指向已分配内存区域的指针,您可以使用任何您喜欢的数组索引(无论是否在数组范围内)。如果您的数组索引超出了数组的边界,您将访问(并修改,如果您分配给数组元素!)此时内存中的任何内容。这可能会导致异常(如果内存地址在您的进程可访问的区域之外),或者可能导致几乎任何事情发生(更改程序中的另一个变量,更改操作系统中的某些内容,格式化硬盘,等等 - 它称为“未定义行为”)。
When you declare a local, static or global array in C++, the compiler needs to know at that point the size of the array, so it can allocate the memory (and free it for you when it goes out of scope). So the array size must be a constant.
当您在 C++ 中声明局部、静态或全局数组时,编译器此时需要知道数组的大小,以便它可以分配内存(并在超出范围时为您释放它)。所以数组大小必须是一个常数。
However, an array is just a pointer. So, if you want an array whose size you don't know at compile time, you can make one on the heap, using "new". However, you then take on the responsibility of freeing that memory (with "delete") once you have finished with it.
然而,数组只是一个指针。因此,如果您想要一个在编译时不知道其大小的数组,您可以使用“new”在堆上创建一个。但是,一旦完成该内存,您就负责释放该内存(使用“删除”)。
I would agree with the posters above to use a vector if you can, as that gives you the kind of protection from accessing stuff outside the bounds of the array that you are used to.
如果可以的话,我同意上面的海报使用向量,因为这可以保护您免于访问您习惯的数组范围之外的内容。
But if you want the fastest possible code, use an allocated array:
但是,如果您想要最快的代码,请使用分配的数组:
class C {
int [] x;
void method A(int size)
{
x = new int[size]; // Allocate the array
for(int i = 0; i < size; i++)
x[i] = i; // Initialise the elements (otherwise they contain random data)
B();
delete [] x; // Don't forget to delete it when you have finished
// Note strange syntax - deleting an array needs the []
}
void method B()
{
int n;
cin >> n;
cout << x[n];
// Be warned, if the user inputs a number < 0 or >= size,
// you will get undefined behaviour!
}
}