關於malloc,結構體的小例子

回顧了一下C語言中的malloc用法和結構體相關的知識點

/*
10點49分
測試malloc動態分配一維數組
測試動態內存分配的跨函數調用

*/

#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>
#include <string.h>

int test01()
{
	int* pAddr = NULL;
	int len = 0;
	printf("請輸入需要分配的數組大小:");
	scanf("%d", &len);
	pAddr = (int*)malloc(sizeof(int) * len);

	//給動態申請的數組分配數值
	int i;
	for (i = 0; i < len; ++i)
	{
		scanf("%d", &pAddr[i]);
	}

	for (i = 0; i < len; ++i)
	{
		printf("%d ", pAddr[i]);
	}

	free(pAddr);

	system("pause");
	return 0;
}

//動態內存分配的跨函數調用
void func(int** p)
{
	//在這個函數內 對q進行一個賦值操作
	//**p = 5;		//error 沒有分配一個內存 會存在錯誤
	*p = (int*)malloc(sizeof(int));
	**p = 5;
}

int test02()
{
	int* q = NULL;
	func(&q);
	printf("%d \n", *q);
	
	free(q);
	return 0;
}

/*
結構體變量和結構體指針變量作爲函數參數傳遞
通過函數完成對結構體的輸入和輸出
一般通過結構體指針變量來進行參數的傳遞
*/

struct Student
{
	int age;			//4
	float score;		//8
	char name[19];		//21
};

typedef struct Student student;

void InputValueForStruct(student *std)
{
	std->age = 26;
	strcpy(std->name, "JamesWu");
	std->score = 99.9f;
}

void ShowStructValue(const student *std)
{
	printf("name:%s\nage:%d\nscore:%f\n", std->name, std->age, std->score);
}

int test03()
{
	student st;
	printf("Student結構體所佔的字節數:%d\n", sizeof(st));
	InputValueForStruct(&st);
	ShowStructValue(&st);

	return 0;
}

/*
最簡單的排序方法
冒泡排序法
*/

void sortArray(int* pArr, int len)
{
	int i, j, temp;
	for (i = 0; i < len-1; i++)
	{
		for (j = 0; j < len - i - 1; j++)
		{
			if (pArr[j] > pArr[j+1])	//大於表示升序 小於表示降序
			{
				temp = pArr[j];
				pArr[j] = pArr[j+1];
				pArr[j+1] = temp;
			}
		}
	}

}

void showArray(const int* pArr, int len)
{
	int i;
	for (i = 0; i < len; ++i)
	{
		printf("%d ", pArr[i]);
	}
	printf("\n");
}

int test04()
{
	int a[6] = { 10,2,3,4,5,6 };
	int i = 0;
	 
	sortArray(a, 6);
	showArray(a, 6);

	return 0;
}



 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章