简体   繁体   中英

Reverse array with using pointers in C

#include <stdio .h>
#include <stdlib .h> 
int main(){
    char text1 [N] ; 
    char reverse [N] ;
    char* txtptr = text1 ;
    char* revtxtptr = reverse ;
    int N;
    printf (”\n Enter any text here : ”) ;
    scanf(”%s”, text1); 
    while(N> 0){
        txtptr --;
        *revtxtptr = *txtptr ;
        revtxtptr++;
    }
    *revtxtptr = ’\0’;
    printf (”The reverse text is : %s \n” , reverse) ;
    return 0; 
}

I want to see here output the reverse form of the input. Something like input:

CLEARLY

output:

YLRAELC

Could you help me to fix my fault?

Here are corrections to your code:

  1. You have spaces before the .h> in the #include lines.
  2. You should limit the size of the buffers.
  3. N is not initialized.
  4. N is not being decremented.
  5. txtptr is not being placed at the end of the C string, but it is being decremented in the while loop.
  6. scanf is not limited to the size of the buffer(s) minus 1.
  7. You need to either find the size of the string using strlen or walk the string until you find '\0'. (forward direction instead)
  8. You use the wrong double-quotes and single quotes ("smart" quotes)

Here is a safe code that will reverse the input array (not in-place):

#include <stdio.h>
#include <stdlib.h>

#define MAXSTR 255
#define STR_HELPER(x) #x
#define STR(x) STR_HELPER(x)

int main() {
  char text1[MAXSTR + 1];
  char revbuf[MAXSTR + 1];
  char* txtptr = text1;
  char* reverse = revbuf + MAXSTR;
  printf("\nEnter any text here : ");
  scanf("%" STR(MAXSTR) "s", text1);
  *reverse = '\0';
  while(*txtptr) {
    *--reverse = *txtptr++;
  }
  printf ("The reverse text is : %s \n" , reverse) ;
  return 0;
}

Here you have an example function for int array.

int *reverseINTarray(int *array, size_t size)
{
    int *end, *wrk = array;
    if(array && size > 1)
    {
        end = array + size - 1;
        while(end > wrk)
        {
            int tmp = *wrk;
            *wrk++ = *end;
            *end-- = tmp;
        }
    }
    return array;
}

or

int *reverseINTarray(const int *src, int *dest, size_t size)
{
    int *wrk = dest;
    if(src && dest && size)
    {
        wrk += size - 1;
        while(size--)
        {
            *wrk-- = *src++;
        }
    }
    return dest;
}

Your "swap two bytes" logic is... simply... wrong. Does this give you any ideas?

char temp;
temp = *chartxtptr;
*chartxtptr = *txtptr;
*txtptr = temp;

You can't "swap" any two bytes without using a temporary to hold the byte that is about to be replaced.

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