简体   繁体   English

在C中反转字符串的函数-如果字符串文字是什么?

[英]Function to reverse a string in C - What if is a string literal?

I have coded the following function that will reverse a String in C: 我编写了以下函数,它将在C中反转一个String:

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 您不能这样做,字符串文字是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. 也许,您需要复制字符串,就像您在第一个示例中所做的一样,在第一个示例中,您使用字符串文字初始化了char数组。

You better of copying string to some other temp string. 您最好将字符串复制到其他临时字符串。

  1. Use another char* to copy original string. 使用另一个char*复制原始字符串。 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. 

The problem is C history. 问题是C历史。

char *a = "Hello"; should be const char *a = "Hello"; 应该是const char *a = "Hello"; . But const came in after C was successful so char *a = "Hello"; 但是const在C成功之后才出现,所以char *a = "Hello"; was allowed to remain OK syntax. 被允许保留OK语法。

Had code been const char *a = "Hello"; 代码是否为const char *a = "Hello"; , reverse(a); reverse(a); would generate a warning (or error). 会产生警告(或错误)。

To modify create something like: 修改创建类似:

char *reverse(char *dest, const char *src);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM