There are no strings of type char *
. A string is a sequence of characters terminated with the zero-character '\0'
.
In this declaration (that has a typo char a* = "abcd";
)
char *a = "abcd";
there is declared a pointer to a string literal. The string literal itself has the type char[5]
. But used as an initializer expression it is implicitly converted to a pointer to its first element of the type char *
.
And you are trying to change the string literal pointed to by the pointer within the function reverse
.
However you may not change a string literal. Any attempt to change a string literal results in undefined behavior.
From the C Standard (6.4.5 String literals)
7 It is unspecified whether these arrays are distinct provided their
elements have the appropriate values. If the program attempts to
modify such an array, the behavior is undefined.
What you could do is to create a new string that will store characters of the source string literal in the reverse order.
For example
char * reverse_copy( const char *s )
{
size_t n = strlen( s );
char *t = malloc( n + 1 );
if ( t != NULL )
{
t += n;
*t = '\0';
while ( *s ) *--t = *s++;
}
return t;
}
And the function can be called like
char *s = "abcd";
char *p = reverse_copy( s );
if ( p != NULL ) puts( p );
free( p );
Here is a demonstration program.
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
char *reverse_copy( const char *s )
{
size_t n = strlen( s );
char *t = malloc( n + 1 );
if (t != NULL)
{
t += n;
*t = '\0';
while (*s) *--t = *s++;
}
return t;
}
int main( void )
{
char *s = "abcd";
char *p = reverse_copy( s );
if (p != NULL) puts( p );
free( p );
}
The program output is
dcba