Pointer Arithmetic


I am a programmer beginning to learn C++. I wrote this chunk of code:

/////////////////////////////////////////////////////////////// Get to do some pointer arithmetic!/////////////////////////////////////////////////////////////#include #include const char NL = '
';const char TB = '	';char* ReverseString(char *pStr);void main(){	char *str = "This is a wild test string...";	char *ch = &str[0];	for (unsigned i=0;i

This code compiles without any error warnings. However, when I execute the code, the program crashes with an Access Violation error. In debugging I found that the offending line is in the ReverseString function, and I encounter the Access Violation error at the following statement:

	*f = *b;

I compiled the same program in C++ Builder 3.0. The program compiled successfully, and on execution it worked perfectly fine. So, the problem lies with Visual C++ 6.0 compiler.

Let me provide the system configuration.

Platform: Intel

Operating System: Windows 2000 RC2

Development Environment: Visual C++ 6.0 Enterprise Edition SP3

Why is this error happening?


Your reverse() function attempts to modify a const array of chars, which is a disallowed operation. Remember that every string literal is a constant, and so is str in this statement:

char *str = "This is a wild test string...";

First, never use plain char * when pointing to a literal string. Use const char * instead:

const char *str = "This is a wild test string...";

Now if you try to compile the const version, your compiler will flag the reverse() call in main() as an error. What you should do is use an array of char rather than a pointer:

char str[] = "This is a wild test string...";

This should be OK.

Share the Post:
Share on facebook
Share on twitter
Share on linkedin


The Latest

microsoft careers

Top Careers at Microsoft

Microsoft has gained its position as one of the top companies in the world, and Microsoft careers are flourishing. This multinational company is efficiently developing popular software and computers with other consumer electronics. It is a dream come true for so many people to acquire a high paid, high-prestige job

your company's audio

4 Areas of Your Company Where Your Audio Really Matters

Your company probably relies on audio more than you realize. Whether you’re creating a spoken text message to a colleague or giving a speech, you want your audio to shine. Otherwise, you could cause avoidable friction points and potentially hurt your brand reputation. For example, let’s say you create a

chrome os developer mode

How to Turn on Chrome OS Developer Mode

Google’s Chrome OS is a popular operating system that is widely used on Chromebooks and other devices. While it is designed to be simple and user-friendly, there are times when users may want to access additional features and functionality. One way to do this is by turning on Chrome OS