I have coded the following function that will reverse a String in C:
void reverse(char *str) {
int length = strlen(str) - 1;
for (int i=0; i < length/2; i++) {
char tmp = str[i];
str[i] = str[length - i];
str[length - i] = tmp;
}
}
This works if I do this:
char a[]="Hello";
reverse(a);
But if I call it passing a string literal, such as:
char *a = "Hello";
It won't work.
So, how would I modify my function so that it can accept string literals and reverse them?
You can not do that, string literals are constants in C
Perhaps, you need to copy the string, much like you do it in your first example, where you initialize a char array using a string literal.
You better of copying string to some other temp string.
char*
to copy original string. Allocate sufficient memory. char *a1 = "Hello"; char* copy_a1 = malloc(sizeof(char)*(strlen(a1)+1)); strncpy(copy_a1, a1, strlen(a1)); copy_a1[strlen(a1)] = '\\0'; reverse(copy_a1); //free memory used.
The problem is C history.
char *a = "Hello";
should be const char *a = "Hello";
. But const
came in after C was successful so char *a = "Hello";
was allowed to remain OK syntax.
Had code been const char *a = "Hello";
, reverse(a);
would generate a warning (or error).
To modify create something like:
char *reverse(char *dest, const char *src);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.