你好,我对编程有点陌生,我正在尝试用 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/