我刚刚写了一个非常简单的字符串反转函数,遇到了一个我无法理解的问题:
void reverse(char *data) {
int length = 0,i;
char *temp,*start,*end;
start = data;
end = data;
length = strlen(data);
end = end + (length -1);
for(i=0; i< length/2; i++) {
*temp = *end;
*end = *start;
*start = *temp;
start++;
end--;
}
}
int main()
{
int length1 = 0;
char data1[100] = "I am megharaj from india";
printf("data1 %s\n", data1);
reverse(data1);
printf("reversed\n");
printf("data1 %s\n", data1);
return 0;
}
这会产生分段错误,但是如果我将其更改为char *temp
,char temp
则一切正常,如下所示:
void reverse(char *data) {
int length = 0,i;
char temp,*start,*end;
start = data;
end = data;
length = strlen(data);
end = end + (length -1);
printf("length %d\n", length);
for(i=0; i< length/2; i++) {
temp = *end;
*end = *start;
*start = temp;
start++;
end--;
}
}
无法理解原因;你能解释一下吗?