c - Xcode c bad_acces 代码 2 错误

标签 c string xcode reverse string-literals

你好,我对编程有点陌生,我正在尝试用 c 编写一个反转字符串的函数。

char *ft_strrev(char *str)
{
char x;
int i = 0,j = 0,k;

while(str[i] != '\0')
{
    i++;
}
k = i;
while(j < k/2)
{
    x = str[j];
    str[j] = str[i]; //here is the error
    str[i] = x;
    j++;
    i--;
}

return str;
}

当我将 abc 放入函数中时,我想得到 cba。

最佳答案

对于初学者来说,此代码片段包含一个逻辑错误。

x = str[j];
str[j] = str[i]; //here is the error
str[i] = x;

对于索引i的初始值,str[i]等于'\0'。因此结果将得到一个空字符串。

代码片段应如下所示

x = str[j];
str[j] = str[i-1]; //here is the error
str[i-1] = x;

至于错误,看来您正在尝试反转字符串文字。您不能更改字符串文字。任何修改字符串文字的尝试都会导致未定义的行为。

来自 C 标准(6.4.5 字符串文字):

7 It is unspecified whether these arrays are distinct provided their elements have the appropriate values. If the program attempts to modify such an array, the behavior is undefined.

您可以通过以下方式调用该函数,声明一个字符数组并使用字符串对其进行初始化。

char s[] = "abc";

ft_strrev( s );

关于c - Xcode c bad_acces 代码 2 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47617351/

相关文章:

java - 使用 JAVA 将字符串拆分为多个部分并存储为 CSV

ios - 将 String 转换为 NSDate 奇怪的格式

ios - 在 Xcode 中得到预期的类型

java - "inherently thread-safe"是什么意思?

c++ - 左移一个 'double' 操作数

c - PostQuitMessage() 是否进入 WM_DESTROY 或 WM_CLOSE?

javascript - 正则表达式不匹配

c - 如何使用 exec() 命令运行 a.out

java - 如何在java中将字符串拆分为数字和字母

xcode - 如何点击 tvOS 模拟器中的选项卡?