the chap6 struct
1. basics of structures
//1. define a struct
way 1:struct point {
int x;
int y;
};
way 2:struct point {
int x;
int y;
}p_test, *p_pointer;
way 3:struct {
int x;
int y;
}point; //this point just only a variale such as a from statement : int a;
/*this define a struct point that is similar type int
declare a struct point variable such as :*/
//2. declare a struct
struct point p1, p2; //just like declare a normal variable except add precedence struct
//3. initialize struct variable p1
way 1 : p1.x = 1;
p1.y = 2;
way 2 : define and initialize
struct point p1 = {1, 2};
//4. struct of pointer,and handle it's members(x, y)
struct point *p;
p = &p1;
p ->x = 4;
p ->y = 5;
2. structures and functions
//1. return a pointer to struct point
struct point makepoint(int x, int y)
{
struct point temp;
temp.x = x;
temp.y = y;
return temp;
}
3. arrays of structures
//declare array of struct just like char test[10];
struct point pointTable[100];
4. pointers to structures
struct point *p_test; //p_test is pointer to the struct point
5. self-referential structures
//define a tree node
struct tnode {
char *value;
struct tnode *left;
struct tnode *right;
}
6. table lookup
struct nlist {
struct nlist *next; //the next pointer to the next ectry
char *name;
}
struct nlist *nlistTab[];//just like pointer array
7. typedef
//typedef for creating new data type names. for example ,the declaration
typedef int _int;
typedef char *string;
typedef struct tnode *tnode_pointer;
typedef struct tnode {
char *value;
tnode_pointer left;
tnode_pointer right;
}Treenode; //creating two type : tnode_pointer and Treenode
8. unions
union {
int ival;
float fval;
char *sval;
} u;
union u_tay {
int ival;
float fval;
char *sval;
};
union u_tay {
int ival;
float fval;
char *sval;
} u;
9. bit-fields
struct {
unsigned int is_keyword : ; //is_keyword width is 1 that maining the it's size is 1 bit
unsigned int is_extern : ;
unsigned int is_static : ;
} flags;
flags.is_keyword = ;
#ifndef STDFSH
#define STDFSH 1
#include "stdfs.h"
#endif
/*
有一點我就很疑惑,對注釋和字元串的處理,是儲存還是忽略不管呢
因為上一個getword是忽略了\/**\/ 和 “” 這個些符号之後會繼續處理
他們裡面的内容,是以我這裡就是忽略到他們裡面的内容,其餘的幾個課後題
我發現了解不了,然後去看答案,發現和題目也不是很對照啊,是以就留着
以後有空在解決把,就把書上的tree的搞一個就可以了。
getword : get next word or character from input
*/
extern int getch();
extern void ungetch(int c);
int getword(char *word, int lim)
{
int c, temp;
char *w = word;
while (isspace(c = getch()))
;
if (c != EOF)
*w++ = c;
if (isalpha(c) || c == '_' || c == '#')
for ( ;--lim > ; ) {
*w++ = c = getch();
if (!isalnum(c) && c != '_') {
ungetch(c);
break;
}
}
else if (c == '\'' || c == '"') {
for ( ;temp = getch() ; )
if (temp == c || temp == EOF)
break;
}
else if (c == '/') {
if ((temp = getch()) == '*') {
for ( ;temp = getch(); )
if (temp == EOF || temp == '*' && getch() == c)
break;
} else
ungetch(temp);
}
*--w = '\0';
if (temp == EOF)
return EOF;
return c;
}
int comment()
{
int c;
while (c=getch() != EOF)
if (c == '*')
if ((c = getch()) == '/')
break;
else
ungetch(c);
return c;
}