devxlogo

Pointer Arithmetic

Pointer Arithmetic

Question:

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?

Answer:

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.

See also  Why ChatGPT Is So Important Today
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist