我正在尝试实现一个代码,该代码使用一个名为“reverse”的函数,该函数接受一个字符串并返回一个与旧字符串相反的新字符串。据我所知,该函数本身工作正常 - 即我测试了反转字符串:新字符串是否具有正确的值,并且确实如此。然而,当我在返回主函数后尝试打印这个反向字符串时,我得到了错误的访问代码。有人有什么想法吗?这是我的代码:
#include <stdio.h>
#include <string.h>
char reverse( char *string) {
char newstring[50]; //reversed string to be returned to the main function
int size = strlen(string);
int index = 0;
for (index = 0 ; index < size ; index++) {
newstring[index] = *(string+size-index-1); //creates a new string that is the reverse of the old string
}
return newstring; //reurns the new string
}
int main(int argc, const char * argv[]) {
char string[50];
printf("Please enter a string you wish to reverse:\n");
scanf("%49s", string); // user enters a string of maximum length 50
int size = strlen(string);
char *reverse_string;
reverse_string = reverse(string); // sets a pointer called reverse_string to the pointer returned by the reverse function
for ( int index = 0 ; index < size ; index++) {
printf("%c", *(reverse_string+index));// prints the reversed string value by value
}
return 0;
}
最佳答案
您需要更改函数的声明,以便它返回 char* 而不仅仅是 char。在您的主循环中,您当前正在将一个字符分配给reverse_string而不是一个char*。
关于函数可以返回字符串作为其输出吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27308559/