[英]Reverse string function in C?
這是我嘗試測試的 C 源代碼:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
main()
{
char c[81];
gets(c);
str_inv(c);
puts(c);
}
void str_inv(char *s[])
{
int i, j;
char *temp;
temp=calloc(1 ,strlen(s)*sizeof(char));
if(temp==NULL)
{
fprintf(stderr, "Error: Memory not allocated.");
exit(1);
}
for(i=0, j=strlen(s)-1; i<strlen(s); i++, j--)
{
temp[i]=s[j];
}
for(i=0; i<strlen(s); i++)
{
s[i]=temp[i];
}
free(temp);
}
程序的輸出如下所示:
**abc**
**Process returned 0 (0x0) execution time : 2.262 s**
**Press any key to continue.**
函數str_inv
的代碼在main()
函數中工作正常,但在單獨的函數中不起作用。
功能有什么問題?
char *s[]
是指向char
的指針數組
char s[]
是一個char
數組
將函數更改為
void str_inv(char s[])
作為旁注。 不推薦使用gets()
,請不要使用它。 請改用fgets()
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.