我想要一个关于你从main调用反向文本的函数的帮助.然而,该程序工作,"或多或少",但它崩溃.这是代码的外观
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void reverse(char * array, int numberOfChars) {
int begin = 0;
int end = 0;
char temp;
end = strlen(&array) - 1;
printf("%s", &array);
while (begin < end) {
temp = array[begin];
array[begin] = array[end];
array[end] = temp;
begin++;
end--;
}
}
int main() {
reverse('supm', 4);
return(0);
getchar();
}
Run Code Online (Sandbox Code Playgroud)
字符串被反转为mpus,但随后崩溃,显然似乎数组只能接受4个字符,如果我将其更改为5而整数值为5,则根本不起作用.任何帮助,将不胜感激.
strlen(&array)并且printf("%s", &array);错了.它们将传递指针所在的位置而不是字符串所在的位置.使用strlen(array)和printf("%s", array);.
reverse('supm', 4); 也是错误的,因为这个调用的第一个参数不是字符串而是实现定义的整数.
请注意,只是将其更改为reverse("supm", 4);不起作用,因为不允许修改字符串文字.
此外,最后一个getchar();将不会被执行,因为它是在之后return 0;.
试试这个:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
void reverse(char * array, int numberOfChars) {
int begin = 0;
int end = 0;
char temp;
end = strlen(array) - 1;
printf("%s", array);
while (begin < end) {
temp = array[begin];
array[begin] = array[end];
array[end] = temp;
begin++;
end--;
}
}
int main() {
char supm[] = "supm";
reverse(supm, 4);
puts(supm); /* added this to see if this code is working well */
return(0);
}
Run Code Online (Sandbox Code Playgroud)
也许您应该使用参数numberOfChars而不是strlen(array)因为您传递参数,但它根本不使用.
| 归档时间: |
|
| 查看次数: |
2484 次 |
| 最近记录: |