指针跟踪数组

C语言 码拜 9年前 (2015-11-27) 1077次浏览
#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.
解决方案:20分
没有指针指针的运算!
只有指针加减一个整数,或两个指针相减的运算
16行之所以对,是原因是两指针相减后得到的是一个整数,然后就变成指针与整数相加

CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明指针跟踪数组
喜欢 (0)
[1034331897@qq.com]
分享 (0)