检查回文。用指针的运算替换数组下标追踪数组的位置

请问,主函数和被调用函数都可以用指针运算替换数组下标吗?怎么做?

#include// 检查输入的句子是不是回文
#include
#define LEN 100
int compare(const char str[],int n);

int main(void)
{
char ch,str_1[LEN];
int i=0;
printf("Enter a message:");
while((ch=getchar())!='\n')//输入句子
if(toupper(ch)<=90&&toupper(ch)>=65)//是字母就存入数组
str_1[i++]=ch;
if(compare(str_1,i)==1)//调用compare函数,返回1是回文
printf("Plindrome\n");
else if (compare(str_1,i)==0)//调用compare函数,返回0不是回文
printf("Not a Plindrome\n");
return 0;
}

int compare(const char str[],int n)//检测回文的函数。
{
int i=0,a,b,flag;
for(i=0;i<=(n/2)-1;i++){
a=toupper(str[i]);
b=toupper(str[(n-1)-i]);
if(a!=b){
flag=0;
break;
}
else
flag=1;
}
return flag;
}

数组下标的底层就是指针,举个例子:

int ar[10]={1,2,3,4,5,6,7,8,9,10};
2[arr]=arr[2]=*(arr+2);//这是相等的

所以能看懂这个你就能很容易改成指针了

这是底层汇编代码:


    printf("arr[2]=%d\n", arr[2]);
001E837E B8 04 00 00 00       mov         eax,4  
001E8383 D1 E0                shl         eax,1  
001E8385 8B F4                mov         esi,esp  
001E8387 8B 4C 05 D0          mov         ecx,dword ptr arr[eax]  
001E838B 51                   push        ecx  
001E838C 68 C8 CC 1E 00       push        1ECCC8h  
001E8391 FF 15 B4 01 1F 00    call        dword ptr ds:[1F01B4h]  
001E8397 83 C4 08             add         esp,8  
001E839A 3B F4                cmp         esi,esp  
001E839C E8 66 8F FF FF       call        __RTC_CheckEsp (01E1307h)  
    printf("2[arr]=%d\n", 2[arr]);
001E83A1 B8 04 00 00 00       mov         eax,4  
001E83A6 D1 E0                shl         eax,1  
001E83A8 8B F4                mov         esi,esp  
001E83AA 8B 4C 05 D0          mov         ecx,dword ptr arr[eax]  
001E83AE 51                   push        ecx  
001E83AF 68 D4 CC 1E 00       push        1ECCD4h  
001E83B4 FF 15 B4 01 1F 00    call        dword ptr ds:[1F01B4h]  
001E83BA 83 C4 08             add         esp,8  
001E83BD 3B F4                cmp         esi,esp  
001E83BF E8 43 8F FF FF       call        __RTC_CheckEsp (01E1307h)  
    printf("*(arr+2)=%d\n", *(arr + 2));
001E83C4 8B F4                mov         esi,esp  
001E83C6 8B 45 D8             mov         eax,dword ptr [ebp-28h]  
001E83C9 50                   push        eax  
001E83CA 68 E8 CC 1E 00       push        1ECCE8h  
001E83CF FF 15 B4 01 1F 00    call        dword ptr ds:[1F01B4h]  
001E83D5 83 C4 08             add         esp,8  
001E83D8 3B F4                cmp         esi,esp  
001E83DA E8 28 8F FF FF       call        __RTC_CheckEsp (01E1307h) 

结果截图:
图片说明

在某些特定情况是可以的,当你定义了一个指针变量并且赋予了它初值,例如你定义了 int * p=&a; 你可以使用p[1],p[2]...,编译器不会指出
这样有什么错误,但是p[i]表示内存中变量a之后的第I个元素,编译器并没有分配这些内存给你使用,这些内存中所存储的东西可能会因为你的
某些操作被改变,这样会发生不可预知的错误。所以不能直接拿指针代替数组,除非内存已经被编译器分配,也就是指针指向了一个数组,这
样他使用的是已分配的内存。