#include <stdio.h> #define MAX 100 int main(){ char str[MAX+1],*change,temp,ch,*p; int i=0,n=0; p=str; change=str; printf("Enter a message:"); while((ch=getchar())!=""\n""&&(p-str)<MAX){ *p++=ch; } *p=""\0""; while((change-str)<((p-str+1)/2)){ temp=*change; *change=*(p-1-change+str); *(p+str-1-change)=temp; change++; } printf("%s",str); }
上面代码编译时会报错:17 [Error] invalid operands to binary + (have “”char *”” and “”char *””)
但假如把17行括号里的内容改成和16行右边一样就不会,这是原因是什么啊?
解决方案:20分
Pointer Arithmetic
Additive operations involving a pointer and an integer give meaningful results only if the pointer operand addresses an array member and the integer value produces an offset within the bounds of the same array. When the integer value is converted to an address offset, the compiler assumes that only memory positions of the same size lie between the original address and the address plus the offset.
This assumption is valid for array members. By definition, an array is a series of values of the same type; its elements reside in contiguous memory locations. However, storage for any types except array elements is not guaranteed to be filled by the same type of identifiers. That is, blanks can appear between memory positions, even positions of the same type. Therefore, the results of adding to or subtracting from the addresses of any values but array elements are undefined.
Similarly, when two pointer values are subtracted, the conversion assumes that only values of the same type, with no blanks, lie between the addresses given by the operands.
Additive operations involving a pointer and an integer give meaningful results only if the pointer operand addresses an array member and the integer value produces an offset within the bounds of the same array. When the integer value is converted to an address offset, the compiler assumes that only memory positions of the same size lie between the original address and the address plus the offset.
This assumption is valid for array members. By definition, an array is a series of values of the same type; its elements reside in contiguous memory locations. However, storage for any types except array elements is not guaranteed to be filled by the same type of identifiers. That is, blanks can appear between memory positions, even positions of the same type. Therefore, the results of adding to or subtracting from the addresses of any values but array elements are undefined.
Similarly, when two pointer values are subtracted, the conversion assumes that only values of the same type, with no blanks, lie between the addresses given by the operands.
解决方案:20分