指针就算指向了常量也不能修改这个常量

先来看我这个低级的错误代码
#include <stdio.h>

int main(int argc, char *argv[])
{
	char *ch1,*ch2;
	int i=0;
	ch1="you are my father";
	ch2="i am your sun";
	do
	{
		ch1[i]=ch2[i];
		i++;
	}while(ch2[i]!='');
	ch1[i]='';
	printf("string=%s",ch1);
	return 0;
}

当运行时直接出来main.exe停止工作,仔细检查时发现char指针指向了常量,我这相当于在修改常量,但是常量是不能修改的。我分析了一下,我可能想的字符串常量是以数据形式存储的,然后直接用char指针指向了其首元素。


另外数据组名也是常量,不能对修改数据组名的值(地址)

char str[]={"i love china"}
str=str+1;
printf("str=%s",str);
这是错误的。

原文地址:https://www.cnblogs.com/JSD1207ZX/p/9386256.html