C++"动态"数组

0 c++ arrays

我在C++中对数组有一些问题/误解.

int myArray[30];
myArray[1]=2;
myArray[2]=4;
Run Code Online (Sandbox Code Playgroud)

这会吐出很多编译器错误.我不认为有必要将它们包含在这里,因为对于每个有C(++)经验的人来说这是一个简单的问题

  • 为什么这不起作用?
  • 有没有办法创建一个具有固定值的"动态"数组(因此不需要malloc)但我可以在运行时更改值?

R S*_*hko 14

我猜你有一个功能之外的东西.

您可以在函数外部定义变量.您甚至可以在函数外部调用任意代码,前提是它是变量定义的一部分.

// legal outside of a function
int myArray[30];

int x = arbitrary_code();

void foo()
{

}
Run Code Online (Sandbox Code Playgroud)

但是你不能在函数之外拥有任意的语句或表达式.

// ILLEGAL outside a function
myArray[1] = 5;

void foo()
{
    // But legal inside a function
    myArray[2] = 10;
}
Run Code Online (Sandbox Code Playgroud)

  • 哦,花哨的裤子去透视徽章.:) (4认同)