【发布时间】:2009-12-03 07:44:47
【问题描述】:
我正在帮助一位朋友完成一些 C++ 作业。我警告说朋友,我做的那种编程(PHP、Perl、Python)与 C++ 完全不同,而且我不能保证我不会说可怕的谎言。
我能够回答他的问题,但并非没有绊倒我自己的动态背景。当我重新熟悉 C++ 数组语义时,我做了一些像这样愚蠢的事情(简化示例以使我的问题更清楚)
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
char easy_as_one_two_three[] = {'A','B','C'};
int an_int = 1;
//I want an array that has a length of the value
//that's currently in an_int (1)
//This clearly (to a c++ programmer) doesn't do that.
//but what is it doing?
char breaking_things[an_int];
cout << easy_as_one_two_three << endl;
return 1;
}
当我编译并运行这个程序时,它会产生以下输出
ABC????
但是,如果我注释掉我的虚假数组声明
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
char easy_as_one_two_three[] = {'A','B','C'};
int an_int = 1;
//I want an array that has a length of the value
//that's currently in an_int (1)
//This clearly (to a c programmer) doesn't do that.
//but what is it doing?
//char breaking_things[an_int];
cout << easy_as_one_two_three << endl;
return 1;
}
我得到了我期望的输出:
ABC
那么,这里到底发生了什么?我(模糊地)理解,当你创建一个数组时,你指向一个特定的内存地址,当你给数组一个长度时,你是在告诉计算机“为我保留下一个 X 块”。
我不明白的是,当我在数组声明中使用变量时,我在告诉计算机做什么,为什么会对完全独立的数组产生影响?
编译器是g++,版本字符串是
science:c++ alanstorm$ g++ -v
Using built-in specs.
Target: i686-apple-darwin9
Configured with: /var/tmp/gcc/gcc-5493~1/src/configure --disable-checking -enable-werror --prefix=/usr --mandir=/share/man --enable-languages=c,objc,c++,obj-c++ --program-transform-name=/^[cg][^.-]*$/s/$/-4.0/ --with-gxx-include-dir=/include/c++/4.0.0 --with-slibdir=/usr/lib --build=i686-apple-darwin9 --with-arch=apple --with-tune=generic --host=i686-apple-darwin9 --target=i686-apple-darwin9
Thread model: posix
gcc version 4.0.1 (Apple Inc. build 5493)
【问题讨论】:
-
您的输出与 an_int 或使用变量指定长度的数组声明无关。
-
@Murali 我更新了我的帖子来解释为什么我认为虚假输出与数组声明有关。
-
@Alan 这很有趣。
-
即使您将虚假部分注释掉,它也不总是打印 ABC - 请参阅我的更新。
-
如果使用 g++,您应该始终使用 -Wall 和 -pedantic 标志编译代码。