C++错误的具体解决方案:变量't'正在使用未初始化

C++ specific solution to the error: variable 't' is being used without being initialized

本文关键字:初始化 错误 解决方案 变量 C++      更新时间:2023-10-16

下面的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和其他现代操作系统会阻止你访问内存,导致你的程序崩溃。为了避免程序崩溃,应该在使用指针之前对其进行初始化。

也可以使用空闲内存初始化指针。这允许动态分配内存。它对于建立链表或数据树等结构非常有用,在这些结构中,您不知道在编译时需要多少内存,因此您必须在程序执行期间获取内存。