1 2 3 4 5 6 7 | int main() { char * str = new char[32]; str = "Hello, Piggy!"; return 0; } |
这样是会内存泄漏的……而我一直都不知道……不过想来也自然,因为这样是允许的,char *str = “Hello, Piggy!”;,“程序中的字符串被存放在常量存储区”不要把这句话当成耳旁风,谨记。
1 2 3 4 5 6 7 | int main() { char * str = new char[32]; str = "Hello, Piggy!"; return 0; } |
这样是会内存泄漏的……而我一直都不知道……不过想来也自然,因为这样是允许的,char *str = “Hello, Piggy!”;,“程序中的字符串被存放在常量存储区”不要把这句话当成耳旁风,谨记。
对最简单的SDBMHash(char*)做了一个简单的测试。随机生成200个长度为31的字符串,利用SDBM得到一个Hash值,然后用直接取余法插入长度为113的HashSet,为简单起见,只是将HashSet对应的位置进行加一。
1 2 3 4 5 6 7 8 9 10 11 | // SDBM Hash Function unsigned int SDBMHash (char *str) { unsigned int hash = 0; while (*str) { hash = (*str++) + (hash << 6) + (hash << 16) - hash; } return (hash & 0x7FFFFFFF); } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | int main() { string word; cin>>word; int len = word.length()-1; long psb = 1; for (int i = 0;i < len;i++) { psb *= 2; } int *flags = new int[len]; for (int i = 0;i < psb;i++) { int temp = i; for (int j = 0;j < len;j++) { flags[j] = temp%2; temp = temp/2; } if(i>0) { for (int j = 0;j < len;j++) { cout<<word[j]; if(flags[j] == 1)cout<<"-"; } cout<<word[word.length()-1]<<endl; } } } |
看了Linux内核代码linux/string.h中的一些字符串操作函数,有几个写的真是漂亮!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | /** * strstr - Find the first substring in a %NUL terminated string * @s1: The string to be searched * @s2: The string to search for */ char *strstr(const char *s1, const char *s2) { int l1, l2; l2 = strlen(s2); if (!l2) return (char *)s1; l1 = strlen(s1); while (l1 >= l2) { l1--; if (!memcmp(s1, s2, l2)) return (char *)s1; s1++; } return NULL; } |
char ** s; s是一个指针1,指向一个指针2, 指针2指向char const char ** s; s是一个指针1,指向一个指针2,指针2指向char,char是常数 char * const * s; s是一个指针1,指向一个常量1,常量1是个指针2,指针2指向char const char * const * s; s是一个指针1,指向一个常量1,常量1是个指针2,指针2指向char,char是常数 const char * const * const s; s是一个常量1,常量1是一个指针1,指针1指向一个常量2,常量2是个指针2,指针2指向char,char是常数
最后,感谢Felix的精彩解析!