C++错误的具体解决方案:变量't'正在使用未初始化
C++ specific solution to the error: variable 't' is being used without being initialized
下面的c++程序可以很好地编译,但是在运行(Runtime check failure
)时给出以下错误:
变量't'未初始化就被使用
#include <iostream>
#include<conio.h>
using namespace cv;
using namespace std;
void foo (int * count)
{
*count=90;
}
int main()
{
int *t;
foo(t);
cout<<t[0]<<endl;
return 0;
}
我将在C中删除这个错误,像这样:
int main()
{
int *t;
t= (int *) malloc(sizeof(int));
foo(t);
cout<<t[0]<<endl;
getch();
return 0;
}
这个错误的c++解决方案是什么?
除非有特殊原因,否则最好在堆栈上分配而不是在堆上分配:
#include <iostream>
void foo (int *count)
*count = 90;
}
int main() {
int t;
foo(&t);
std::cout << t << "n";
}
如果你真的必须在堆上分配,最好使用智能指针(比如std::unique_ptr
),而不是拥有原始指针:
#include <iostream>
#include <memory>
void foo (int *count) {
*count = 90;
}
int main() {
auto t = std::make_unique<int>(); // C++14
// auto t = std::unique_ptr<int>(new int()); // C++11
foo(t.get());
std::cout << *t << "n";
}
则不需要调用delete
(或c++ 14中的new
)。
指针在使用之前应该初始化为指向特定的内存地址。如果不是这样,它可以指向任何东西。这可能会给程序带来非常不愉快的后果。例如,操作系统可能会阻止您访问它知道您的程序不拥有的内存:这将导致程序崩溃。如果它允许你使用内存,你就可以乱动任何正在运行的程序的内存——例如,如果你在Word中打开了一个文档,你可以更改文本!幸运的是,Windows和其他现代操作系统会阻止你访问内存,导致你的程序崩溃。为了避免程序崩溃,应该在使用指针之前对其进行初始化。
也可以使用空闲内存初始化指针。这允许动态分配内存。它对于建立链表或数据树等结构非常有用,在这些结构中,您不知道在编译时需要多少内存,因此您必须在程序执行期间获取内存。
相关文章:
- 使用默认构造函数引用成员变量初始化错误
- 交换机案例语句中的初始化错误
- 英特尔 MKL 稀疏 QR 求解 C++ 返回未初始化错误
- 在模板类中使用"this"会导致参数初始化错误
- 映射的映射集的映射初始化错误
- C++图形初始化错误(语法或丢失文件缺陷?
- QSQLDATABASE:SIGSEV初始化错误
- 映射的 std::for_each() 给出无效的初始化错误
- 初始化错误过多
- C++初始化错误 std::set
- 简单的类构造函数初始化错误
- 组合框初始化错误:无法读取未定义的属性'constructor'
- OpenCV卡尔曼滤波器初始化错误
- C++11动态数组部分列表初始化(错误或误解)
- C++ 静态变量在发布模式下初始化错误
- Visual Studio 2010 SP1 中的 64 位整数初始化错误
- C++libPNG-简单初始化错误
- 结构数组-初始化错误
- 初始化错误
- 我不断收到函数初始化错误.(运行时检查失败 #3)