使用C中的指针反转字符串的程序 [英] Program to reverse a string using pointers in C
问题描述
你好伙计们我试图通过从函数返回指向char的指针来反转字符串的程序
我试过的:
hello guys i am trying to make c program for reversing the string by returning the pointer to char from the function
What I have tried:
#include<stdio.h>
#include<stdlib.h>
char* reversestring(char* input);
int main()
{
int i;
char* output;
char inputstring[100];
printf("enter the string\n");
gets(inputstring);
output = reversestring(inputstring);
i希望以两种方式打印相同的字符串,即使用printf和运行循环请建议我双向打印在相同的程序
这里我已经采取i = 0到4的固定字符串在这里假设用户将输入长度为5字符的固定字符串,因为我不知道正确的方法
i want to print the same string in both way that is by using printf and by running the loop please suggest me both way to print in same program
here i have taken i=0 to 4 for fixed string here i m assuming that user will enter a fixed string of length 5 char because i dont know the proper way
printf("%s\n",output);
for(i=0;i<4;i++) {
printf("%c",(output+i));
}
}
从这里开始反转功能
reverse function start from here
char* reversestring(char* input)
{
int count=0,begin,end;
char* output=(char*) malloc(100);
while(*input!=0) {
count++;
}
end=count-1;
for(begin=0;begin<count;begin++) {
*(output+begin)=*(input+end);
end--;
}
output[begin]='\0';
return output;
}
没有错误并警告它输入的只是没有给出输出(光标闪烁只有程序没有结束)
there is no error and warning it is taking input only not giving the output(cursor is blinking only program is not ending)
推荐答案
这个循环不会完成:
This loop won't finish:
while(*input!=0) {
count++;
}
您可以将其替换为:
You could replace it with:
while (*(input + count) != 0) {
count++;
}
To print your reversed string character by character, use strlen[^]:
for (int i = 0; i<strlen(output); i++) {
printf("%c", *(output + i));
}
在我看来,内存分配应该是来电者责任。此外,永远不要使用获取
功能。
尝试
In my opinion the memory allocation should be caller responsibility. Moreover, never ever usegets
function.
Try
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char * reverse( char * rev, const char * str, size_t length )
{
size_t n;
for (n=0; n<length; ++n)
{
rev[n] = str[length-1-n];
}
rev[n] ='\0';
return rev;
}
int main()
{
char s[100];
printf("please enter the string:\n");
if ( ! fgets( s, sizeof(s), stdin) ) return -1;
size_t length = strlen(s);
char * r = (char *) malloc( length+1 );
if ( ! r ) return -2;
reverse( r, s, length);
printf("reversed: %s\n", r);
free(r);
return 0;
}
这篇关于使用C中的指针反转字符串的程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!