I am writing a function to reverse a string. It compiles fine, but
when I run it under VS6.0, it says "The instruction at 0X004011
reference memory at 0x0042e00. The memory could not be written."
Any ideas??
I have an idea. I'm guessing that you are trying to test your
code by calling it with a string literal like this:
reverseString("my test string");
or
char * test = "my test string";
reverseString(test);
Am I right? If so, then you are trying to write into a string
literal in this function and that is something that you should
not do.
Now to the code:
void reverseString(char* s)
{ char temp;
char* s1 = new char[strlen(s) + 1];
^^^
"new" does not exist in C. This is C++ code and off-topic here.
I'll be nice and assume that you were not aware of this. If
you want to allocate memory in C, use malloc(). The way you
would do that in this case is to #include <stdlib.h> and then:
char * s1 = malloc(strlen(s)+1);
if (s1 == NULL)
exit(EXIT_FAILURE);
You are, of course, free to do something more user-friendly than
exit(EXIT_FAILURE) if malloc fails.
for (int i=0; i<strlen(s)/2; i++)
{ temp = s;
s[strlen(s)-1-i] = temp;
s1 = s[strlen(s)-1-i];
s1[strlen(s)-1-i] = temp;
This code is totally confused and won't reverse anything. Look
at what is going on:
Beginning of loop, i == 0:
+---+ +---+---+---+---+---+ +---+---+---+---+---+
temp: | | s: | Y | u | c | k | 0 | s1: | ? | ? | ? | ? | ? |
+---+ +---+---+---+---+---+ +---+---+---+---+---+
+---+ +---+---+---+---+---+ +---+---+---+---+---+
temp: | Y | s: | Y | u | c | k | 0 | s1: | ? | ? | ? | ? | ? |
+---+ +---+---+---+---+---+ +---+---+---+---+---+
+---+ +---+---+---+---+---+ +---+---+---+---+---+
temp: | Y | s: | Y | u | c | k | Y | s1: | ? | ? | ? | ? | ? |
+---+ +---+---+---+---+---+ +---+---+---+---+---+
+---+ +---+---+---+---+---+ +---+---+---+---+---+
temp: | Y | s: | Y | u | c | k | Y | s1: | Y | ? | ? | ? | ? |
+---+ +---+---+---+---+---+ +---+---+---+---+---+
s1[strlen(s)-1-i] = temp;
+---+ +---+---+---+---+---+ +---+---+---+---+---+
temp: | Y | s: | Y | u | c | k | Y | s1: | Y | ? | ? | ? | Y |
+---+ +---+---+---+---+---+ +---+---+---+---+---+
Work out the rest by yourself and then figure out how to do it
correctly. Hint: you don't need s1 at all unless you want the
reversed string to be separate from the original string. If that
is actually what you want, then return the newly allocated
string from the function.
-Sheldon