33,311
社区成员
发帖
与我相关
我的任务
分享
#include<stdio.h>
#define ROWS 3
#define COLS 4
int sum2d(int rows,int cols,int ar[rows][cols]);
int main(void)
{
int i,j;
int rs=3;
int cs=10;
int junk[ROWS][COLS]={
{2,4,6,8},
{3,5,7,9},
{12,10,8,6} //2唯数组
};
int morejunk[ROWS-1][COLS+2]={
{20,30,40,50,60,70},
{5,6,7,8,9,10}
}; //另一个二维数组
int varr[rs][cs];
for(i=0;i<rs;i++)
for(j=0;j<cs;j++)
varr[i][j]=i*j+j; //变长数组,不知道到底什么叫变长数组
printf("3x5 array\n");
printf("Sum of all elements=%d\n",sum2d(ROWS,COLS,junk)); //调用函数计算第一个二维数组的和
printf("2x6 array\n");
printf("Sum of all elements=%d\n",sum2d(ROWS-1,COLS+2,morejunk);//调用函数计算第二个二维数组的和
printf("3x10 VLA\n");
printf("Sum of all elements=%d\n",sum2d(rs,cs,varr)); //调用函数计算变长数组的和
return 0;
}
int sum2d(int rows,int cols,int ar[rows][cols])//通常函数定义都是sum(int ar[][cols]),这个怎么可以列也可以传递值?
{
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;
}
//使用动态分配
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
int i,L;
char *p;
void main() {
for (i=0;i<20000;i++) {
L=rand();
p=malloc(L);
if (NULL==p) {
printf("malloc error!\n");
continue;
}
memset(p,0,L);
free(p);
}
}
//不使用动态分配
#include <stdio.h>
#include <stdlib.h>
#include <memory.h>
#define MAXLEN 30000
int i,L;
char buf[MAXLEN];
char *p;
void main() {
p=&buf[0];
for (i=0;i<20000;i++) {
L=rand();
if (L>MAXLEN) {
printf("L>MAXLEN==%d, ignore spilth.\n",MAXLEN);
L=MAXLEN;
}
memset(p,0,L);
}
}
//在堆中开辟一个4×5的二维int数组
#include <stdio.h>
#include <malloc.h>
int **p;
int i,j;
void main() {
p=(int **)malloc(4*sizeof(int *));
if (NULL==p) return;
for (i=0;i<4;i++) {
p[i]=(int *)malloc(5*sizeof(int));
if (NULL==p[i]) return;
}
for (i=0;i<4;i++) {
for (j=0;j<5;j++) {
p[i][j]=i*5+j;
}
}
for (i=0;i<4;i++) {
for (j=0;j<5;j++) {
printf(" %2d",p[i][j]);
}
printf("\n");
}
for (i=0;i<4;i++) {
free(p[i]);
}
free(p);
}
// 0 1 2 3 4
// 5 6 7 8 9
// 10 11 12 13 14
// 15 16 17 18 19