1. 程式人生 > >寫入位置發生衝突,該如何解決

寫入位置發生衝突,該如何解決

關於:字串處理的時候出現 寫入位置0x004157a8時發生訪問衝突解決。

字串可以使用如下表示:

char hello1[]  = "Hello";

char hello2[] =  {"Hello"};

char hello3[] = {'H','e','l','l','o','/0'};

char hello4 = "Hello';

這裡需要注意的是,hello1,hello2,hello3是等價的,hello4是一個指標,且hello4中指向的"Hello"位於常量去,如果不小心會出錯的。下面是一個例子:

// 字串和指標.cpp : 定義控制檯應用程式的入口點。
//

#include "stdafx.h"
#include <string.h>


int _tmain(int argc, _TCHAR* argv[])
{
	//char *pStr = "abc";  //"abc"字串在常量區,pStr指標在棧區
	//char p[] = "abc";    //這裡的"abc"的在棧區,
	
	//printf("%s\n",pStr);
	//printf("%d\n",strlen(pStr));

	//printf("%c\n",p[0]);
	//printf("%c\n",pStr[0]);
	//char *p1 = p;
	//char *p2 = p;
	//*p1 = *p2;

	//char *p11 = pStr;
	//char *p21 = pStr;
	//char tmp = *p11;

	//*p21 = *p11;

	//printf("%c\n",*p1);

	char *p = "I love you!"; //字串"I love you"在常量區,p在棧區
	printf("%c\n", *p);

	//*p = 'P';  //這句是不對的,因為*p指向常量去的'I',是不能被修改的。

	char p1[] = "I love you"; //p1在棧區

	*p1 = 'P';   //可以修改,因為p1是一個數組,相當於p1[11] = {'I',' ', 'l','o','v','e',' ','y','o','u'}
	
	printf("%c\n",*(p1+2));
	printf("%s\n", p1);


	return 0;
}


參考