#include<stdio.h>
#include<string.h>
#include<iostream.h>
using namespace std;
int main()
{
const char *a="hello";
char *b;
strcpy(b,a);
cout<<b;
return 0;
}
This code theows memory exception . why ?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
char* bis a pointer that is yet to be pointed at any memory… it simply holds a random address. You attempt to copy the content ofaover the memory at that address. Instead, first pointbat some memory – either a local array or fromnew char[].( or simply copy it directly into
buffer🙂 )BTW, C++ has a
<string>header that’s much, much easier to use:If you’re writing new code, prefer std::string, but sooner or later you’ll need to know about all that
char*stuff too, especially when C++ code needs to interact with C libraries.