> ## Content Index
> Fetch the complete content index at: https://sgpublic.xyz/llms.txt
> Use this file to discover other available public pages before exploring further.

# C 语言关于 char* 的坑
- URL: https://sgpublic.xyz/p/2025/02/6aac9cb1810a480001533607/
- Published: 2025-02-18T11:50:00.000Z
- Updated: 2025-02-18T11:50:00.000Z
- Author: Haven Madray
- Tags: 软件开发, C/C++, #wp-post

咱也不是主修 C/C++ 的，但最近看到一个题，代码如下：

```c
#include "stdio.h"
#include "string.h"
void fun(char *w, int n);
int main() {
char *s = "1234567";
fun(s, strlen(s));
puts(s);
return 0;
}
void fun(char *w, int n) {
char t, *s1, *s2;
s1 = w;
s2 = w + n - 1;
while (s1 < s2) {
t = *s1++;
*s1 = *s2--;
*s2 = t;
}
}
```

如果仔细分析代码，一步一步慢慢执行，也能得出答案是 "1711717"。但我实际跑起来的时候，在 `*s1 = *s2--;` 处崩溃了。

经过网上冲浪得到答案，使用 `char *s = "1234567";` 这种方式声明的字符串属于常量，是不可修改的，而上文提到的那一行就是在修改这个常量，所以程序崩掉了。

正确写法应该如下：

```c
#include "stdio.h"
#include "stdlib.h"
#include "string.h"
void fun(char *w, int n);
int main() {
char *s = (char *)malloc(8 * sizeof(char));
strcpy(s, "1234567");
fun(s, strlen(s));
puts(s);
return 0;
}
void fun(char *w, int n) {
char t, *s1, *s2;
s1 = w;
s2 = w + n - 1;
while (s1 < s2) {
t = *s1++;
*s1 = *s2--;
*s2 = t;
}
}
```

就是说应该开辟一块内存，然后把常量复制进去，这样就能得到一个能修改的字符串了。

虽然咱不常写 C，过了这段时间久了不用肯定就忘了，但记下来总归是好的。