c++ 精髓

 得此篇,可弃WinDbg。

c语言开发,容易出错的就是内存开辟与释放,领悟此篇代码,从此告别崩溃。

typedef struct Field
{
	char*		key;
	char*		value;
}Field;

//二级指针计数
int ptrCount(void **papszStrList)
{
	int items = 0;
	if (papszStrList)//papszStrList
	{
		while (*papszStrList != NULL)
		{
			items++;
			papszStrList++;
		}
	}

	return items;
}

int freeArray(void** &items)
{
	if (items == NULL)
		return 1;

	int i = 0;
	for (; items[i] != NULL; i++)
	{
		delete[] items[i]; items[i] = NULL;
	}

	if (items != NULL)
	{
		delete[] items; items = NULL;
	}

	return 0;
}

int frees(void** &items)
{
	if (items == NULL)
		return 1;

	int i = 0;
	for (; items[i] != NULL; i++)
	{
		free(items[i]); items[i] = NULL;
	}

	if (items != NULL)
	{
		free(items); items = NULL;
	}

	return 0;
}

void assignment(Field**&ptr)
{
	int len = ptrCount((void**)ptr);
	for (size_t i = 0; i < len; i++)
	{
		strcpy_s(ptr[i]->key,64,"123");
		strcpy_s(ptr[i]->value, 64, "abc");
	}
}

void assignments(char**&ptr)
{
	int len = ptrCount((void**)ptr);
	for (size_t i = 0; i < len; i++)
	{
		strcpy_s(ptr[i], 64, "123");
	}
}

int main()
{
	
	//---------------------------char类型----------------------------//
	char** test1 = new char*[4];
	char** test2 = (char**)calloc(4, sizeof(char*));
	//---------------------------自定义类型----------------------------//
	Field** test3 = new Field*[4];
	Field** test4 = (Field**)calloc(4, sizeof(Field*));

	size_t i = 0;
	for (;	i < 3; i++)
	{
		test1[i] = new char[64];
		*(test2 + i) = (char*)calloc(64, 1);

		test3[i] = new Field;
		test3[i]->key = new char[64];
		test3[i]->value = new char[64];
		//--------------------语法*(test4 + i)==test4[i]----------------//
		*(test4 + i) = (Field*)calloc(64, 1);
		(*(test4 + i))->key = (char*)calloc(64, 1);
		test4[i]->value = (char*)calloc(64, 1);
	}
	test1[i] = NULL;
	test2[i] = NULL;

	test3[i] = NULL;
	i[test4] = NULL;//语法i[test4]==test4[i]

	assignments(test1);
	freeArray((void**&)test1);
	assignments(test2);
	frees((void**&)test2);

	assignment(test3);
	freeArray((void**&)test3);
	assignment(test4);
	frees((void**&)test4);
}

可弃WinDbg。

上一篇:golang 报错illegal rune literal


下一篇:UnicodeDecodeError gbk codec can't decode byte in position illegal multibyte sequence