【发布时间】:2017-12-22 08:41:38
【问题描述】:
#include<stdio.h>
#define ASIZE 50
void Reverse(char *str){
int Asize,i=0;
char temp;
// Find the length of the string
while(*(str+i)!='\0'){
i++;
}
Asize=i;
// string reverse
for(i=0;i<(Asize/2);i++){
temp = *(str+i);
//may be below is some error with first input method 1
//but for input method 2 it works perfectly
*(str+i) = *(str+(Asize-(i+1)));
*(str+(Asize-(i+1))) = temp;
}
}
int main()
{
//input method 1. (error aries while i pass the pointer as argument)
char *s = "abcxyz";
//input method 2 (works perfectly while as function parameter)
char s[ASIZE];
scanf("%s",s);
Reverse(s);
printf("%s",s);
}
在主输入法 1 中,输入法 1 不能完美地用于反转字符串,但方法 2 有效。 我的概念对 char 指针的内存表示不清楚。也许我不擅长正确地提出问题,但有人请让我清楚为什么方法 1 不起作用。提前感谢您的帮助。
【问题讨论】:
-
修改字符串常量是未定义的行为
-
@n.caillou GCC 有选项
-Wwrite-strings在这种情况下会发出警告。