【问题标题】:Segmentation fault when reversing string in C [duplicate]在C中反转字符串时出现分段错误[重复]
【发布时间】:2023-03-31 10:43:01
【问题描述】:

我有以下代码,其主要目的是反转字符串的字符。因此,例如,字符串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),因为我没有遍历所有数组,而只是遍历了其中的一半。我说的对吗?

【问题讨论】:

  • O(n/2) == O(0.5 * n) == O(c * n) == O(n),所以反转字符串在O(n)
  • char str[] = "Y U SEGMENTATION FAULT?";
  • 真的很抱歉。我没有看到其他问题。是重复的。
  • 这个问题之前已经被问过很多次了,我很惊讶自动搜索没有返回任何结果。

标签: c string segmentation-fault


【解决方案1】:

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

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

或将其设为本地数组(将字符串放入堆栈):

char[] str = "It's OK now";

【讨论】:

  • 但是根据stackoverflow.com/questions/8732325/how-to-declare-strings-in-c -- 如果我用指针声明我的字符串,我可以修改它,对吧?
  • 不,您可以按照 hmjd 的建议将您的字符串声明为本地数组,这将是另一回事。
  • @HommerSmith char *foo = "bar";char foo[] = "bar"; 之间的区别之一是初始化方法。前者将只读数组转换为指针并存储指针。后者将只读数组复制到一个新的可修改数组中。
猜你喜欢
  • 2013-02-28
  • 1970-01-01
  • 2011-03-11
  • 2013-08-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-03
相关资源
最近更新 更多