Mail Archives: djgpp/1997/12/14/12:33:00
This is a multi-part message in MIME format.
--------------6BF03C5726B3
Content-Type: text/plain; charset=us-ascii
Content-Transfer-Encoding: 7bit
Following is a commented standard C solution:
--------------6BF03C5726B3
Content-Type: text/plain; charset=us-ascii; name="Reverse.c"
Content-Transfer-Encoding: 7bit
Content-Disposition: inline; filename="Reverse.c"
/*
* Your code mixes C++ with C, which will not compile as C code. I'm
* assuming you are studying C and not C++, so here is a fixed program that
* reversed strings.
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char *Reverse(char *String)
{
int Length = strlen(String);
char * Copy = (char *)malloc(Length + 1);
int Offset;
/*
* The above line mallocs the length of the string + 1 byte for the
* terminating zero (which is how strings are terminated in C). Since
* Copy is just a pointer to memory, you MUST allocate memory for Copy to
* point to. Otherwise the program will not run properly (if it runs at
* all).
* malloc() returns NULL if the memory couldn't be allocated, so our
* program must check for the condition. If the return value is NULL, then
* the program can't continue. Since the return type of Reverse() is a
* pointer, common practice advises us to return NULL if an error occurs.
*
*/
if (Copy == NULL)
return NULL;
/*
* Set the memory pointed-to by Copy to all zeros. This will ensure that
* the string has a terminating zero and will set the memory to a known
* value.
*/
memset(Copy,0,Length + 1);
/*
* Now go through the string backwards to build Copy
*/
for (Offset = 0;Offset < Length;Offset++)
Copy[Offset] = String[Length - Offset - 1];
/*
* Return the copied string to the caller. Don't forget that Copy was
* allocated from the memory pool by Reverse(), but not yet returned to the
* memory pool (this would be foolish to do since Copy hasn't been used by
* the caller yet). So be sure the calling program frees the memory after
* it uses Copy (this is done in main() below).
*/
return Copy;
}
int main(void)
{
char String[] = "The string itself is";
char * Copy = Reverse(String);
if (Copy == NULL)
{
printf("Copy returned NULL. Ending program prematurely.\n");
return 1;
}
printf("\"%s\" is: %s\n",String,Copy);
free(Copy);
return 0;
}
/*
* Compile this program with the following command-line:
*
* gcc -Wall -s reverse.c -o reverse.exe
*
*/
--------------6BF03C5726B3--
- Raw text -