C语言——请问如何不使用额外的数组空间?

不使用额外的数组空间,将一个字符串按逆序重新存放。

编译器:VC++ 6.0

我的代码:

#include<stdio.h>
#include<string.h>


void main(void)
{
   char a[100],temp;
   puts("please input the string:");
   gets(a);
   for(int j=0;j<strlen(a)-1;j++)
       for(int k=0;k<strlen(a)-j-1;k++)
       {
           temp=a[k+1];
           a[k+1]=a[k];
           a[k]=temp;
       }
    puts("the reverse string:");
    puts(a);

}

尝试使用malloc函数:

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


void main(void)
{
   char a[100],temp;
   char *str;
   puts("please input the string:");
   gets(a);
   str=(char*)malloc(sizeof(a));
   for(int i=0;i=sizeof(a);i++)
       *(str+i)=a[i];
   for(int j=0;j<strlen(str)-1;j++)
       for(int k=0;k<strlen(str)-j-1;k++)
       {
           temp=str[k+1];
           str[k+1]=str[k];
           str[k]=temp;
       }
    puts("the reverse string:");
    puts(str);
    free(str);

}

 

出现情况:

请问如果不使用额外的数组空间,我知道要用malloc函数但是我不知道具体该怎么用,应该怎么去编写这个程序?谢谢大家能帮忙看看

你直接在a上面交换比较行了?为啥要创建新数组?

len = strlen(a);

for(int i = 0; i < len/2; i++){

  temp = a[i];

  a[i] = a[len-i];

  a[len-i] = temp;

}