简体   繁体   English

CPP访问冲突错误

[英]CPP access violation Error

I keep getting this Error: access violation at 0x40496a: write of address 0x0. 我不断收到此错误: 0x40496a处的访问冲突:写地址0x0。 I'm using Borland C++. 我正在使用Borland C ++。

This is my source code. 这是我的源代码。

#include<iostream.h>
#include<conio.h>
#include<stdio.h>
int main()
{
    char *nm;
    cout<<"\n Enter a name: ";
    gets(nm);
    cout<<"\n Name: "<<nm;
    getch();
    return 0;
}

Even if I set char *nm=NULL or use cin>> for input I'm getting the same error. 即使我设置了char * nm = NULL或使用cin >>作为输入,我也会遇到相同的错误。 Please Help, Thanks. 请帮助,谢谢。

When you declare nm you don't initialize it, that means the value of nm is indeterminate, it doesn't really point anywhere (in reality it points to a seemingly random location). 当您声明nm您无需初始化它,这意味着nm的值是不确定的,它实际上并未指向任何地方(实际上,它指向一个看似随机的位置)。 You need to make it point to something big enough to hold the string you input. 您需要使其指向足以容纳您输入的字符串的东西。

Using uninitialized variables, and NULL pointers, leads to undefined behavior whose most common result is a crash. 使用未初始化的变量和NULL指针会导致未定义的行为,其最常见的结果是崩溃。

To fix this, either make it point to an already initialized array: 要解决此问题,请使其指向已初始化的数组:

char str[20];
char* nm = str;

Or allocate memory for the string dynamically: 或动态地为字符串分配内存:

char* nm = new char[20];

Or even better, don't use character pointers as string, and especially not the gets function (it's dangerous and have even been removed from the C standard), use the C++ std::string class instead and std::getline function to fetch a line: 甚至更好的是,不要使用字符指针作为字符串, 尤其 不要使用gets函数(这很危险,甚至已经从C标准中删除),而应使用C ++ std::string类和std::getline函数来获取一条线:

std::string nm;
std::getline(std::cin, nm);

Or if you just want to get a single space-delimited word, use the normal input operator: 或者,如果您只想获取一个以空格分隔的单词,请使用常规输入运算符:

std::string nm;
std::cin >> nm;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM