未初始化的局部变量
uninitialized local variable
这段代码编译并运行,但给出了我无法修复的Microsoft编译器错误
警告 C4700:使用了未初始化的局部变量"。
这是代码的最后一行,我认为
#include <iostream>
using namespace std;
const int DIM0 = 2, DIM1 = 3, DIM2 = 4, DIM3 = 5;
void TestDeclar();
int main(){
TestDeclar();
cout << "Done!n";
return 0;
}
void TestDeclar(){
//24 - array of 5 floats
float xa[DIM3], xb[DIM3], xc[DIM3], xd[DIM3], xe[DIM3], xf[DIM3];
float xg[DIM3], xh[DIM3], xi[DIM3], xj[DIM3], xk[DIM3], xl[DIM3];
float xm[DIM3], xn[DIM3], xo[DIM3], xp[DIM3], xq[DIM3], xr[DIM3];
float xs[DIM3], xt[DIM3], xu[DIM3], xv[DIM3], xw[DIM3], xx[DIM3];
//6 - array of 4 pointers to floats
float *ya[DIM2] = {xa, xb, xc, xd}, *yb[DIM2] = {xe, xf, xg, xh};
float *yc[DIM2] = {xi, xj, xk, xl}, *yd[DIM2] = {xm, xn, xo, xp};
float *ye[DIM2] = {xq, xr, xs, xt}, *yf[DIM2] = {xu, xv, xw, xx};
//2 - array of 3 pointers to pointers of floats
float **za[DIM1] = {ya, yb, yc};
float **zb[DIM1] = {yd, ye, yf};
//array of 2 pointers to pointers to pointers of floats
float ***ptr[DIM0] = {za, zb};
cout << &***ptr[DIM0] << 'n';
}
您正在访问超过ptr4D
末尾。 DIM0
是 2,比最后一个索引 1 大 1!
将最后几行更改为:
//array of 2 pointers to pointers to pointers of floats
float ***ptr4D[DIM0] = {za, zb};
cout << &***ptr4D[0] << 'n';
不确定我是否可以帮助您,但我试图找出尝试在我的 Linux 机器上运行它有什么问题。我已经在 ubuntu 机器上编译了它进行比较,它运行良好,甚至告诉编译器打开所有选项警告(传递 -Wall 选项)。跑步时,我得到了这个:
# Compiled it with -Wall to enable all warning flags and -g3 to produce extra debug information
~$ g++ -Wall stackoverflow.cpp -g3
./a.out
Segmentation fault (core dumped)
然后我尝试使用 GDB(GNU 调试器)调试它并得到这个:
(gdb) r
Starting program: /home/ubuntu/a.out
Program received signal SIGSEGV, Segmentation fault.
0x0000000000400986 in TestDeclar () at stackoverflow.cpp:34
34 cout << &***ptr4D[DIM0] << 'n';
(gdb) s
因此,问题似乎出在cout线上。再次检查您的代码,DIM0 的值为 2,因此您正在尝试访问 ptr4D 之外的内存地址。正如user1721424所提到的,只需将DIM0替换为0即可完成!
#After fixing it:
~$ ./a.out
0x7fff74cd3830
Done!
希望对您有所帮助!
相关文章:
- 为什么C++有不同的变量初始化方式?
- 静态 constexpr 成员变量初始化
- C++不同的变量初始化
- 全局和局部变量初始化与 constexpr 的差异背后的基本原理
- 是变量初始化失败吗?
- 视觉C++:在 DLL 加载期间,全局变量初始化顺序是否具有确定性?
- 类静态变量初始化顺序
- 使用 constinit 变量初始化 constexpr 变量
- 是否可以在不修改父类的情况下将成员变量初始化推迟到继承的类?
- 如何将局部变量初始化为C++的未知值
- 使用全局变量初始化不同编译单元中的其他全局变量
- 使用默认构造函数引用成员变量初始化错误
- 宏的 if 语句中的变量初始化
- 不稳定的C :每行适应性变化多变量初始化
- DLL 中的 C++ 静态局部变量初始化会导致_CrtIsValidHeapPointer异常
- C++-局部未初始化变量的值
- 在VS2015中c++局部静态变量初始化线程安全吗?
- 多线程环境中的静态局部变量初始化
- 局部静态变量初始化是线程安全的
- C++11 中线程安全局部静态变量初始化的成本