简体   繁体   English

C中的反向字符串函数?

[英]Reverse string function in C?

Here's a C source I tried to test:这是我尝试测试的 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);
}

An output of the program looks like this:程序的输出如下所示:

**abc**


**Process returned 0 (0x0)   execution time : 2.262 s**
**Press any key to continue.**

The code in function str_inv works fine while in main() function, but not in separate function.函数str_inv的代码在main()函数中工作正常,但在单独的函数中不起作用。

What is the problem with function?功能有什么问题?

char *s[] is an array of pointer to char char *s[]是指向char的指针数组

char s[] is an array of char char s[]是一个char数组

Change the function to将函数更改为

void str_inv(char s[])

As a side note.作为旁注。 gets() is deprecated, please do not use it.不推荐使用gets() ,请不要使用它。 Use fgets() instead.请改用fgets()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM