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?

有帮助吗?

解决方案 2

You better of copying string to some other temp string.

  1. Use another char* to copy original string. Allocate sufficient memory.
  2. Copy sources string to this one. Don't forget to null terminate it.
  3. reverse..
  4. Dont forget to free this memory after use.
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.

其他提示

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.

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);
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top