C语言—复合字面量

作者:追风剑情 发布于:2019-10-13 20:50 分类:C

示例

//Visual Studio中加上这句才可以使用scanf()
//否则只能使用scanf_s()
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdbool.h>

#define COLS 4

int sum2d(const int ar[][COLS], int rows);
int sum(const int ar[], int n);

//argc: 参数个数 argv[]: 参数数组
int main(int argc, char *argv[])
{
	int total1, total2, total3;
	int * pt1;
	int(*pt2)[COLS];

	//右边的写法称为复合字面量
	pt1 = (int[2]) { 10, 20 };//匿名数组
	pt2 = (int[2][COLS]) { {1, 2, 3, -9}, { 4,5,6,-8 } };//匿名数组

	total1 = sum(pt1, 2);
	total2 = sum2d(pt2, 2);
	total3 = sum((int[]) { 4, 4, 4, 5, 5, 5 }, 6);

	printf("total1=%d\n", total1);
	printf("total2=%d\n", total2);
	printf("total3=%d\n", total3);

	system("pause");
	return 0;
}

int sum(const int ar[], int n)
{
	int i;
	int total = 0;
	for (i = 0; i < n; i++)
		total += ar[i];
	return total;
}

int sum2d(const int ar[][COLS], int rows)
{
	int r;
	int c;
	int tot = 0;
	for (r = 0; r < rows; r++)
		for (c = 0; c < COLS; c++)
			tot += ar[r][c];
	return tot;
}

运行测试 
1111.png

标签: C语言

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号