#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void fit(char *p , int n);
int main(void)
{
char *mesg = "Hey, Lisa. You look so beautiful! "; // Line A
puts(mesg);
fit(mesg , 6);
puts(mesg);
system("pause");
return 0;
}
void fit(char *p , int n)
{
if(strlen(p) > n)
*(p + n) = '\0';
}
查看上面的代码。函数拟合设计为通过在位置n + 1中放置'\ 0'来仅显示字符串的前n个字符。问题来了。如果在行A中,* mesg被mesg []替换,程序工作正常。但* mesg不起作用。我使用vs2012。我知道*名称中的名称是一个变量,所以名称++是可以的,而名称[]中的名称是常量,因此名称++是不允许的。除了这个区别之外,在声明一个字符串时不应该使用* name和name []是否相同?*声明字符串时,*名称和名称中的不同*
您可以修改字符数组,但不能修改字符串文字。见http://stackoverflow.com/q/1614723/10077 –
这是一个历史遗产,它不要求'char * mesg'是const char * mesg',但它应该是,改为const char * mesg '和编译器应该在'fit(mesg,6)上出现错误;' – chux