C++ 初始化程序无法确定字符数组的大小
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17575250/
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
Initializer fails to determine size of character array
提问by Jeroen
Whenever I run the code below (Yes that's allthe code) the compiler gives me an error:
每当我运行下面的代码(是的,这就是所有代码)时,编译器都会给我一个错误:
error: initializer fails to determine size of ‘path'
错误:初始化程序无法确定“路径”的大小
What I want to do is copy the contents of argv[0], which is the path of the application as a character array, into the path variable.
我想要做的是将argv[0]的内容,也就是应用程序的路径作为字符数组,复制到path变量中。
int main(int argc, char** argv) {
int offset = 0;
int pathSize = 0;
while(argv[0][pathSize] != 'char path[] = new char[pathSize];
delete &path;
')
pathSize++;
char path[] = new char[pathSize];
delete &path;
return 0;
}
回答by Sabashan Ragavan
Your error is in the below part of your code:
您的错误位于代码的以下部分:
char *path = new char[pathSize];
delete[] path;
Change it to...
将其更改为...
int main(int argc, char* argv[])
{
int size = 34;
char path[size];
return 0;
}
回答by Borgleader
First, char path[]
should be char* path
. Second, its delete[] path;
. If you new[]
you delete[]
if you new
you delete
.
首先,char path[]
应该是char* path
。其次,其delete[] path;
. 如果你new[]
你delete[]
如果你new
你delete
。
There is an extension for gcc (which is not standard mind you) which allows you to do this:
gcc 有一个扩展(这不是您的标准),它允许您执行此操作:
char* path = new char[pathSize];
However this will work only in gcc as this is a gcc extension.
但是,这仅适用于 gcc,因为这是 gcc 扩展。
回答by Josh
You should use a dynamic array.
您应该使用动态数组。
##代码##and as others have mentioned delete is only needed for new, therefore you do need it, but the way your code was written is not how you would normally want to use delete
正如其他人所提到的,delete 只需要 new,因此您确实需要它,但是您的代码编写方式并不是您通常想要使用的方式 delete