简体   繁体   中英

Reverse string function in C?

Here's a C source I tried to test:

#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.

What is the problem with function?

char *s[] is an array of pointer to char

char s[] is an array of char

Change the function to

void str_inv(char s[])

As a side note. gets() is deprecated, please do not use it. Use fgets() instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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