C語言指標和陣列筆試題

sugar high發表於2020-11-03

陣列名錶示陣列首元素的地址:
2個例外:
1.sizeof(陣列名),陣列名錶示整個陣列,計算的是陣列的總大小,單位是位元組

2.&陣列名,陣列名錶示整個陣列,&陣列名去除的是整個陣列地址

一維陣列:

int main()
{
	int a[] = { 1, 2, 3, 4 };
	printf("%d\n", sizeof(a));//16
	printf("%d\n", sizeof(a+0));//4
	printf("%d\n", sizeof(*a));//4
	printf("%d\n", sizeof(a+1));//4
	printf("%d\n", sizeof(a[1]));//4
	printf("%d\n", sizeof(&a));//4
	printf("%d\n", sizeof(*&a));//16 -err
	printf("%d\n", sizeof(&a+1));//4
	printf("%d\n", sizeof(&a[0]));//4
	printf("%d\n", sizeof(&a[0]+1));//4

	return 0;
}

輸出結果:

在這裡插入圖片描述

字元陣列:

int main()
{
	char arr[] = { 'a', 'b', 'c', 'd', 'e', 'f' };
	printf("%d\n", sizeof(arr)); //6
	printf("%d\n", sizeof(arr + 0)); //4
	printf("%d\n", sizeof(*arr)); //1
	printf("%d\n", sizeof(arr[1]));//1
	printf("%d\n", sizeof(&arr)); //4
	printf("%d\n", sizeof(&arr + 1)); //4
	printf("%d\n", sizeof(&arr[0] + 1));//4 
	printf("%d\n", strlen(arr)); //隨機值
	printf("%d\n", strlen(arr + 0));//隨機值
	//printf("%d\n", strlen(*arr)); //err
	//printf("%d\n", strlen(arr[1])); //err
	printf("%d\n", strlen(&arr)); //任意值
	printf("%d\n", strlen(&arr + 1)); //任意值
	printf("%d\n", strlen(&arr[0] + 1));//任意值
	return 0;
}

輸出結果:

在這裡插入圖片描述

int main()
{
	char arr[] = "abcdef"; 
	printf("%d\n", sizeof(arr)); //7
	printf("%d\n", sizeof(arr + 0)); //4
	printf("%d\n", sizeof(*arr));//1
	printf("%d\n", sizeof(arr[1]));//1 
	printf("%d\n", sizeof(&arr)); //4
	printf("%d\n", sizeof(&arr + 1)); //4
	printf("%d\n", sizeof(&arr[0] + 1)); //4

	printf("%d\n", strlen(arr)); //6
	printf("%d\n", strlen(arr + 0));//6
	//printf("%d\n", strlen(*arr)); //err
	//printf("%d\n", strlen(arr[1])); //err
	printf("%d\n", strlen(&arr)); //6
	printf("%d\n", strlen(&arr + 1)); //隨機
	printf("%d\n", strlen(&arr[0] + 1));//5
	char *p = "abcdef";
	printf("%d\n", sizeof(p));//4
	printf("%d\n", sizeof(p + 1)); //4
	printf("%d\n", sizeof(*p));//1
	printf("%d\n", sizeof(p[0])); //1
	printf("%d\n", sizeof(&p));//4
	printf("%d\n", sizeof(&p + 1));//4
	printf("%d\n", sizeof(&p[0] + 1));//4

	printf("%d\n", strlen(p));//6
	printf("%d\n", strlen(p + 1)); //5
	//printf("%d\n", strlen(*p)); //err
	//printf("%d\n", strlen(p[0]));//err
	printf("%d\n", strlen(&p)); //隨機值
	printf("%d\n", strlen(&p + 1)); //隨機值
	printf("%d\n", strlen(&p[0] + 1));//5
	return 0;
}

輸出結果:

在這裡插入圖片描述
二維陣列:

int main()
{
	int a[3][4] = { 0 };
	printf("%d\n", sizeof(a));//48
	printf("%d\n", sizeof(a[0][0])); //4
	printf("%d\n", sizeof(a[0])); //16
	printf("%d\n", sizeof(a[0] + 1)); //4
	printf("%d\n", sizeof(*(a[0] + 1))); //4
	printf("%d\n", sizeof(a + 1)); //4
	printf("%d\n", sizeof(*(a + 1))); //16
	printf("%d\n", sizeof(&a[0] + 1)); //4
	printf("%d\n", sizeof(*(&a[0] + 1))); //16
	printf("%d\n", sizeof(*a));//16
	printf("%d\n", sizeof(a[3]));//16
	return 0;
}

輸出結果:

在這裡插入圖片描述

相關文章