C语言笔记
初始化动态二维矩阵
#include<stdio.h>
#include<stdlib.h>
int** matrix(int height,int width,int initial)
{
int **a=malloc(sizeof *a * height);
printf("Initializing matrix of size %d X %d with initial value %d\n", height,width,initial);
for(int i=0;i<height;i++)
{
a[i]=malloc(sizeof *(a[i]) * width);
for(int j=0;j<width;j++)
{
a[i][j]=initial;
}
}
printf("Printing the matrix...\n");
for(int i=0;i<height;i++)
{
for(int j=0;j<width;j++)
{
printf("%d ",a[i][j]);
}
printf("\n");
}
}
int main(void)
{
int** m=matrix(4,5,0);
return 0;
}
分析复杂变量声明
#include<stdio.h>
#include<string.h>
#include<ctype.h>
#define MAXTOKEN 100
enum { NAME, PARENS, BRACKETS};
void dcl(void);
void dirdcl(void);
int gettoken(void);
int tokentype;
char token[MAXTOKEN];
char name[MAXTOKEN];
char datatype[MAXTOKEN];
char out[1000];
main()
{
while (gettoken() != EOF) {
strcpy(datatype, token);
out[0] = '\0';
dcl();
if (tokentype != '\n')
printf("syntax error\n");
printf("%s: %s %s\n", name, out, datatype);
}
return 0;
}
/* dcl: parse a declarator */
void dcl(void)
{
int ns;
for (ns = 0; gettoken() == '*'; ) /* count *'s */
ns++;
dirdcl();
while (ns-- > 0)
strcat(out, " pointer to");
}
/* dirdcl: parse a direct declarator */
void dirdcl(void)
{
int type;
if (tokentype == '(') { /* ( dcl ) */
dcl();
if (tokentype != ')')
printf("error: missing )\n");
} else if (tokentype == NAME) /* variable name */
strcpy(name, token);
else
printf("error: expected name or (dcl)\n");
while ((type=gettoken()) == PARENS || type == BRACKETS)
if (type == PARENS)
strcat(out, " function returning");
else {
strcat(out, " array");
strcat(out, token);
strcat(out, " of");
}
}
int gettoken(void)
{
int c, getch(void);
void ungetch(int);
char *p = token;
while ((c = getch()) == ' ' || c == '\t')
;
if (c == '(') {
if ((c = getch()) == ')') {
strcpy(token, "()");
return tokentype = PARENS;
} else {
ungetch(c);
return tokentype = '(';
}
} else if (c == '[') {
for (*p++ = c; (*p++ = getch()) != ']'; )
;
*p = '\0';
return tokentype = BRACKETS;
} else if (isalpha(c)) {
for (*p++ = c; isalnum(c = getch()); )
*p++ = c;
*p = '\0';
ungetch(c);
return tokentype = NAME;
} else
return tokentype = c;
}
#define BUFSIZE 100
char buf[BUFSIZE];
int bufp = 0;
int getch(void)
{
return (bufp >0) ? buf[--bufp] : getchar();
}
void ungetch(int c)
{
if (bufp >= BUFSIZE)
printf("üngetch: too many characters\n");
else
buf[bufp++] = c;
}
打印进度条
void progress_bar(const int n, const int tot)
{
int i, pgr = n*50/tot, rem = (tot-n)*50/tot;
printf("\r[");
for (i=0; i<pgr; i++)
printf("#");
for (i=0; i<rem; i++)
printf("-");
printf("]");
}
lambda表达式
#define lambda(lambda$_ret, lambda$_args, lambda$_body)\
// 语句表达式
({\
lambda$_ret lambda$__anon$ lambda$_args\
lambda$_body\
lambda$__anon$;\ // 返回值
})
注释切换代码
#include<stdio.h>
int main(){
/**
printf("1\n");
/*/
printf("2\n");
//*/
/**/
printf("3\n");
/*/
printf("4\n");
//*/
return 0;
}
评论已关闭