简体   繁体   English

程序在不声明char []的情况下反转C中的字符串

[英]Program to reverse a string in C without declaring a char[]

I need to reverse a given string and display it without using the value At[index] notation , I tried the below program using pointers,but it does not print anything for the reverse string, 我需要反转给定的字符串并在不使用值At[index] notation情况下显示它,我尝试了使用指针的以下程序,但对于反转的字符串,它不显示任何内容,

Please help! 请帮忙!

int main()    
{
    char* name=malloc(256);
    printf("\nEnter string\n");
    scanf("%s",name);
    printf("\nYou entered%s",name);

    int i,count;
    count=0;

   //find the length
    while((*name)!='\0')
    {
        count++;
        name++;
    }

    //pointer now at
    printf("\n%p",name);

    printf("\nLength is %d",count);

    name=name+count;
    //pointer now at
    printf("\n%p",name);

    for(i=0;i<(count);i++)
    {   
        printf("%c",(*name));
        name=name-1;
    }

    return 0;
}

Remove name=name+count; 删除name=name+count; because of the name++ in the precedent loop moved name pointer to the '\\0' char; 由于在先例循环中的name++ ,将name指针移到了'\\0'字符;

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

int main()
{
    char* name=malloc(256);
    printf("\nEnter string\n");
    scanf("%s",name);
    printf("\nYou entered%s",name);

    int i,count;
    count=0;

    //find the length and move name pointer
    while((*name)!='\0')
    {
            count++;
            name++;
    }

    //pointer now at
    printf("\nPointer is: %p",name);

    printf("\nLength is: %d\n",count);

    for(i=1;i<=(count);i++)
    {   
        printf("%c",*(name-i));            
    }

    printf("\n");
    return 0;
}

OR change the final loop to 或将最终循环更改为

for(i=0;i<(count);i++)
{   
        name--;
        printf("%c",*name);
}

Remove name=name+count; 删除name=name+count; and add name--; 并添加name--;

Important: scanf(" %s", name); 重要: scanf(" %s", name); has no bounds checking on the input. 没有边界检查输入。 If someone enters more than 255 characters into your program, it may give undefined behaviour. 如果有人在您的程序中输入了255个以上的字符,则可能会产生不确定的行为。

Now, you have the char array you have the count (number of char in the array), and you make name++ (name has the last char offset) then why do you need to bother doing stuffs like this? 现在,有了char array ,就得到了count (数组中char数量),并且使name++ (name具有最后一个char偏移量),那么为什么还要麻烦做这样的事情?

name=name+count; 

Try this: 尝试这个:

#include <stdio.h>

int main()

{
    char* name = malloc(256);
//  char name[256];
    printf("\nEnter string\n");
//  scanf("%s", name);
    fgets(name, 254, stdin); // carriage return and null character (256-2) 
    printf("\nYou entered %s", name);
    int i, count;
    count = 0;
//find the length
    while ((*name) != '\0' && (*name) != '\r') {
        count++;
        name++;
    }
//pointer now at
//  printf("\n%p", name);

//  printf("\nLength is %d", count);

//  name = name + count;
//pointer now at
//  printf("\n%p", name);

    for (i = count; i >= 0; i--) { // starts from last '\0'
        printf("%c", (*name));
        name = name - 1;
    }
    return 0;
}

I got the following output: 我得到以下输出:

Enter string rakeb 输入字符串rakeb

You entered rakeb 您输入了rakeb

bekar 贝卡尔

The easiest way? 最简单的方法? Just replace them with their syntactic equivalent: 只需将它们替换为它们的语法等效项:

arr[index] // is sugar for ...
arr + index

Then, instead of using two indices to traverse just use pointers. 然后,不要使用两个索引来遍历,而要使用指针。 Using this you can actually find a solution pretty easy: 使用此方法,您实际上可以找到一个非常简单的解决方案:

 void nreverse(char * str) {
  char * forward = str;
  char * backward = str + strlen(str) - 1;
  while (forward < backward) {
    char temp = *forward;
    *forward = *backward;
    *backward = temp;
    ++forward;
    --backward;
  }
}

Try this which will not only print but also reverse string and store it in name. 尝试此操作,这不仅会打印,而且还会反转字符串并将其存储在名称中。

#include <stdio.h>

int main()

{
char* name = malloc(256);
char *backup1 = *bakcup2 = name;
printf("\nEnter string\n");
fgets(name, 254, stdin); // carriage return and null character (256-2) 
printf("\nYou entered %s", name);
while ((*backup1) != '\0' && (*backup1) != '\r') {
    backup1++;
}

backup1--; // Because here backup1 was pointing to '\0' or '\r'.
while(backup1 > backup2){
   /* Swapping characters */
    char temp;
    temp = *backup1;
    *backup1 = *backup2;
    *backup2 = temp;
    backup1--;
    backup2++;
}

backup1 = name;
while(*backup1 != '\0' && *backup1 != '\r') {
    printf("%c", (*backup1));
    backup1++;
}
return 0;
}

Please post code that cleanly compiles 请发布干净编译的代码

The current posted code is missing the required/used header files 当前发布的代码缺少必需/已使用的头文件

the following code 以下代码

1) includes error checking
2) limits the length of the user supplied string
   to avoid a input buffer overflow
3) eliminates certain lines (commented out)
   that caused 'name' to point to the wrong location
4) incorporates '\n' at the end of the printf() format strings
   so the info will be printed rather than held 
   in the buffer for stdout
5) at the end, passes the pointer to the malloc'd memory
   to the free() function
6) corrects the loop count when printing the 
   reverse of the input string

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

#define MAX_NAME_LEN (256)

int main()
{
    char* name=NULL;
    char* temp = NULL;

    if( NULL ==(name=malloc(256)) )
    { // then malloc failed
        perror( "malloc for name[] failed");
        exit( EXIT_FAILURE );
    }

    // implied else, malloc successful

    temp = name;  // save ptr to malloc'd memory
    printf("\nEnter string\n");
    if( 1 != scanf("%255s", name) )
    { // then scanf failed
        perror( "scanf for name failed");
        exit( EXIT_FAILURE );
    }

    // implied else, scanf successful

    printf("\nYou entered: %s\n",name);

    int i,count;
    count=0;

   //find the length
    while((*name)!='\0')
    {
        count++;
        name++;
    }

    //pointer now at
    printf("\nAddress of last char in name[]: %p\n",name);

    printf("\nLength is %d\n",count);

    //name=name+count;
    //pointer now at
    //printf("\n%p",name);

    for(i=0;i<=count;i++)
    {
        printf("%c",(*name));
        name--;
    }
    printf( "\n" );

    free(temp);

    return 0;
} // end function: main

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

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