簡體   English   中英

程序在不聲明char []的情況下反轉C中的字符串

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

我需要反轉給定的字符串並在不使用值At[index] notation情況下顯示它,我嘗試了使用指針的以下程序,但對於反轉的字符串,它不顯示任何內容,

請幫忙!

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;
}

刪除name=name+count; 由於在先例循環中的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;
}

或將最終循環更改為

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

刪除name=name+count; 並添加name--;

重要: scanf(" %s", name); 沒有邊界檢查輸入。 如果有人在您的程序中輸入了255個以上的字符,則可能會產生不確定的行為。

現在,有了char array ,就得到了count (數組中char數量),並且使name++ (name具有最后一個char偏移量),那么為什么還要麻煩做這樣的事情?

name=name+count; 

嘗試這個:

#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;
}

我得到以下輸出:

輸入字符串rakeb

您輸入了rakeb

貝卡爾

最簡單的方法? 只需將它們替換為它們的語法等效項:

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

然后,不要使用兩個索引來遍歷,而要使用指針。 使用此方法,您實際上可以找到一個非常簡單的解決方案:

 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;
  }
}

嘗試此操作,這不僅會打印,而且還會反轉字符串並將其存儲在名稱中。

#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;
}

請發布干凈編譯的代碼

當前發布的代碼缺少必需/已使用的頭文件

以下代碼

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