C語言進階:第34課:多維數組和多維指針(難點)

指向指針的指針

指針的本質是變量
指針會佔用一定的內存空間
可以定義指針的指針來保存指針變量的地址值
int main()
{
	int i=0;
	int* p = NULL;
	int** pp = NULL;
	
	pp  = &p;
	
	*pp = &i;
}
爲什麼需要指向指針的指針?
指針在本質上也是變量

對於指針也同樣存在傳值調用和傳址調用

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

int reset(char**p, int size, int new_size)
{
    int ret = 1;
    int i = 0;
    int len = 0;
    char* pt = NULL;
    char* tmp = NULL;
    char* pp = *p;
	
	if( (p != NULL) && (new_size > 0))
	{
		pt = (char*)malloc(new_size);//申請空間

		tmp = pt;
		
		len = (size < new_size) ? size : new_size;
		
		for(i=0; i<len; i++)
		{
			*tmp++ = *pp++;
		}
		
		free(*p);
		*p = pt;
		
		//釋放原有空間
	}
	else
	{
		ret = 0;
	}
	return ret;
}

int main()
{
	char* p = (char*)malloc(5);
	printf("%p\n", p);
	
	if( reset(&p, 5, 3) )  
	//傳址調用 ;第一個參數是一個指針,而p本身就是一個指針,對於數組的修改,就需要用到指針的指針
	{
		printf("%p\n", p);
	}
	
	free(p);
	
	return 0;
}

編譯運行:

~/will$ ./a.out
0x9893008
0x9893018

【二維數組】

二維數組在內存中以一維的方式排布
二維數組中的第一維是一維數組
二維數組中的第二維纔是具體的值
二維數組的數組名可以看做是常量指針

void printfArray(int a[], int size)
{
	int i=0;
	
	printf("printfArray %d\n", sizeof(a));	
	for(i=0; i<size; i++)
	{
		printf("%d  ", a[i]);
	}
	
	printf("\n");
}

int main()
{
	int a[3][3] = {{0, 1, 2}, {3, 4, 5}, {6, 7, 8}};
	int* p = &a[0][0];  //指針p指向二維數組的首地址
	
	int i=0;
	int j=0;
	
	for(i=0; i<3; i++)
	{
		for(j=0; j<3; j++)
		{
			printf("%d ", *(*(a+i) + j)); //使用指針訪問數組元素 *(a+i)->a[i]; *(a[i]+j)->a[i][ij]	}
		
		printf("\n");
	}
	
	printf("\n");
	
	printfArray(p, 9);
	
	return 0;

}

編譯運行:

~/will$ ./a.out
0 1 2 
3 4 5 
6 7 8 

printfArray 4
0  1  2  3  4  5  6  7  8 

一維數組名代表數組首元素的地址

int a[5]  a的類型爲int*

二位數組名同樣代表數組首元素的地址

int m[2][5]  m的類型爲 int(*)[5]

二維數組的類型也決定了二維數組必須確定第二個參數,因爲只有這樣纔可以確定二維數組的類型。

結論:
1、二維數組名可以看做是指向數組的常量指針
2、二維數組可以看做是一維數組
3、二維數組中的每個元素都是同類型的一維數組

malloc()並不能保證申請的內存中的所有值都爲0。

動態申請二維數組:

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

int** malloc2d(int row, int col)
{
	int** ret = NULL;
	
	if((row > 0) && (col > 0))
	{
		ret = (int**)malloc(row * sizeof(int*));  //二維數組以一維的方式進行空間排布
		
		int* p = NULL;
		
		p = (int*)malloc(row * col * sizeof(int));  //注意此處申請的空間大小
		
		if( (ret != NULL) && (p != NULL))
		{
			int i=0;
			
			for(i=0; i<row; i++)
			{
				ret[i] = p + i*col; //本質上可以看做是一維數組
			}		
		}
		else
		{
			free(ret);
			free(p);
			
			ret = NULL;
		}		
	}
			
	return ret;	
}

void free2d(int** p)
{
	if(*p != NULL)
	{
		free(*p);
	}
	
	free(p);
}

int main()
{
	int** a = malloc2d(3, 3);
	int i=0;
	int j=0;
	
	for(i=0; i<3; i++)
	{
		for(j=0; j<3; j++)
		{
			printf("%d, ", a[i][j]);
		}
		
		printf("\n");
	}
	
	free2d(a);
	
	return 0;
}

編譯運行:

~/will$ gcc test.c
~/will$ ./a.out
0, 0, 0, 
0, 0, 0, 
0, 0, 0, 
小結:C語言中只支持一維數組;
C語言中的數組大小必須在編譯期就作爲常數確定;
C語言中的數組元素可是任何類型的數據;
C語言中的數組的元素可以是另一個數組。


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