- 在binary search中得滤,如果全部都是通過ptr來操作原數(shù)組候址,需要注意mid = low + (high - low) / 2.
- 原因在于指針是不可以相加的赏僧。而substraction is legal匿情,結(jié)果就是兩個指針(往往是同一數(shù)組內(nèi)的)的offset的差值。
- 對于一個大小為n的數(shù)組s薪缆,訪問它的&s[n](i.e. s+n) is legal,dereferencing it is illegal.然而對于s[-1]是完全illegal秧廉。
- 不要認(rèn)為一個struct的大小就是所有member大小之和。
- 為了對齊的要求(內(nèi)存中)拣帽,there may be unnamed holes in a structure.
struct {
char c;
int i;
};
需要8個bytes,而不是5個疼电。sizeof works properly here.
for (ptr = head; ptr != NULL; p=p->Next) {
}
是walk through linked list idiom.
(the ptr type)malloc(sizeof(whatever you want)).malloc的返回值是void,需要顯式cast到想要的類型
在C語言中减拭,用-表示空格蔽豺。printf中,%s的幾種變體:%.*s(接參數(shù)), %.10s(經(jīng)測試拧粪,只有precision小于字符串長度的時候才有效,沒有'.'也無效), %-10s(改為左對齊(默認(rèn)情況下是右對齊),字符不夠用空格補), %15.10s(取10個字符修陡,總共占15個字符長度,不夠的用空格補足可霎,right alignment), %-15.10s同上魄鸦,left alignment.
sprintf作用是把一個字符串格式化然后放入一個buffer字符串中,之后就可以使用這個字符串癣朗,而不必自己進(jìn)行對字符數(shù)組的操作拾因,十分方便.(buffer must be big enough to receive the result)
實現(xiàn)minprintf的tricky bit is how minprintf walks along the argument list when list doesn't even have a name.
scanf: except the 1st, the other arguments, each of which must be a pointer, indicate where the corresponding converted input should be stored.
scanf: returning 0 means the next input character does not match the first specification in the format string.The next call to scanf resumes searching immediately after the last character already converted.
sscanf: reads from a string instead of the standard input.return the items assigned value successfully.
scanf: an input field is defined as a string of non-while space characters; it extends either to the next while space or until the field width.(WHITE-SPACE characters are blank, tab, newline(\n), carriage return(return key), veritcal tab, formfeed(進(jìn)紙頁))
No & is used with array name since it is a pointer.
scanf skips over white space(blank, tabs, newlines, etc) as it looks for input values.
scanf: to read input whose format is not fixed, it is often best to read a line at a time, then pick it apart with sscanf.(nice stratage!)
Example:
while (getline(line, sizeof(line)) > 0) {
if (sscanf(line, "%d %s %d", &day, monthname, &year) == 3) {
printf("valid: %s\n", line);
}else if (sscanf(line, "%d/%d/%d", &month, monthname, &year) == 3) {
printf("valid: %s\n", line);
}else {
printf("invalid %s\n", line);
}
}
- binsearch on K & R C:
int binsearch(int x, int v[], int n) {
int low, high, mid;
low = 0;
high = n - 1;
while (low <= high){
mid = (low + high)/2;
if (x < v[mid]) {
high = mid - 1;
}else if (x > v[mid]) {
low = mid + 1;
}else {
return mid;//Found match
}
}
return -1;//no match
}