0

我有以下代码,其主要目的是反转字符串的字符。因此,例如,字符串I love cats将被转换为stac evol I.

#include <string.h>
#include <stddef.h>
#include <stdio.h>

void reverseString(char *str)
{
   int size = strlen(str);
   char *end = str + size - 1;
   char tmp;

   while (end > str) {
     tmp = *str;
     *str = *end;
     *end = tmp;
     end--;
     str++;
   }
}

int main()
{
  char *str = "Y U SEGMENTATION FAULT?";
  reverseString(str);

}

当我运行它时,我得到一个分段错误,我不明白为什么。另外,我的另一个问题是这个函数的时间复杂度(大 O)。我相信它应该是 O(n/2),因为我没有遍历所有数组,而只是遍历了其中的一半。我对吗?

4

1 回答 1

1

您正在尝试修改字符文字,即只读数据段中的字符串。使用 strdup 在堆上复制/复制它,例如:

char *str = strdup("It's OK now");

或者使它成为一个本地数组(将字符串放在堆栈上):

char[] str = "It's OK now";
于 2013-02-12T10:42:14.180 回答