我想实现一个代码,它使用了一个名为reverse的函数,它接受一个字符串并返回一个与旧字符串相反的新字符串。据我所知,函数本身可以正常工作 - 也就是说,我测试了一下,看看反向字符串:new字符串是否具有正确的值,并且它是否正确。但是,当我尝试打印这个反向字符串后,它已被返回到主函数我得到一个错误的访问代码。有没有人有任何想法?这是我的代码:函数可以返回字符串作为它们的输出吗?
#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;
}
函数可以返回字符串的地址,而不是字符串本身。 – chux 2014-12-05 04:05:03
由于'newstring'是一个局部变量,所以返回'newstring'是一个问题。 – chux 2014-12-05 04:06:28
函数可以返回指针。 – 2014-12-05 04:26:04