【发布时间】: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