首先,对不起我的英语,我是法国人。我想写一个函数,my_revstr
。这个函数反转字符串,但是当我测试它不工作时,它启动控制台并崩溃。
要反转我的字符串,我想交换相反的字符,例如:为8 chars 0-7, 1-6, 2-5, 3-4
的字符串。我用一些函数:my_strlen (return the lenght of the string)
, my_swap (swap the values)
,这个函数工作。下面是代码:
char *my_revstr(char *str)
{
int i;
int n;
i = my_strlen(str);
if (i%2 == 1) /* odd str*/
{
i = i/2 - 1;
n = i + 2;
while (i >= 0)
{
my_swap(str + i, str + n);
i = i - 1;
n = n + 1;
}
}
else
{
i = i / 2 - 1;
n = i + 1;
while (i >= 0)
{
my_swap(str + i, str + n);
i = i - 1;
n = n + 1;
}
}
}
下面是测试:
int main()
{
my_putstr(my_revstr("Bonjour"));
return 0;
}
你能帮我理解为什么它不工作吗?
使用字符串字面值(如"Bonjour"
)定义的字符串被认为是只读的。
修改这样的字符串会调用未定义的行为。
第一步是使其可修改:
char text[] = "Bonjour";
my_putstr(my_revstr(text));
这将创建一个字符数组(text
),并且仅使用字符串字面值初始化数组。这意味着在第一行之后,text
只是一个字符数组,您可以像对任何其他变量一样对其进行读/写访问。
另外,你的函数缺少return
语句,所以传递给my_putstr()
的指针也是非常随机的。这又是未定义行为