代码1:
int main()
{
char tmp[20] = "1.04";
printf("float str is %s\n",tmp);
delcharPoint(tmp);
printf("%s\n",tmp);
}
void delcharPoint(char *pStr)
{
char *pTmp = pStr;
int flag_0 = 0;
printf("*pTmp = %s\n",pTmp);
printf("*pTmp = %s\n",pTmp);
if(*pStr == '0')
{
pStr++;
flag_0 = 1;
}
while(*pStr != '\0')
{
if(*pStr != '.')
{
*pTmp++ = *pStr;
pStr++;
}
else
{
pStr++;
if(flag_0 ==1 && *pStr == '0')
{
pStr++;
}
}
}
*pTmp = '\0';
}
这段代码效果很好,打印出来:
float str is 1.04
*pTmp = 1.04
*pTmp = 1.04
104
代码2:
int main()
{
char *tmp = "1.04";
printf("float str is %s\n",tmp);
delcharPoint(tmp);
printf("%s\n",tmp);
}
void delcharPoint(char *pStr)
{
char *pTmp = pStr;
int flag_0 = 0;
printf("*pTmp = %s\n",pTmp);
printf("*pTmp = %s\n",pTmp);
if(*pStr == '0')
{
pStr++;
flag_0 = 1;
}
while(*pStr != '\0')
{
if(*pStr != '.')
{
*pTmp++ = *pStr;
pStr++;
}
else
{
pStr++;
if(flag_0 ==1 && *pStr == '0')
{
pStr++;
}
}
}
*pTmp = '\0';
}
此代码不起作用,它打印:
float str is 1.04
*pTmp = 1.04
*pTmp = 1.04
Segmentation fault
两个代码之间的区别仅在于我在code1中使用char[]
而在code2中使用char *
。我搜索了the difference between char[]
and char *
。但我仍然没有导致这些代码之间的区别
答案 0 :(得分:3)
下面:
char *tmp = "1.04";
"1.04"
是一个字符串文字,字符串文字是不可变的,这意味着它不能被更改。尝试这样做会导致未定义的行为。
另一方面,
char tmp[20] = "1.04";
创建一个char
数组,将"1.04"
复制到其中。修改数组的内容是合法的。