上海网站建设推荐,上海中小企业名录,公司名称大全免费取名,网站设计在线培训C语言经常需要发明各种轮子#xff0c;为方便以后能够把精力放在应用逻辑上而不在发明轮子上#xff0c;把一些常用的代码片段列于此。首先是字符串处理方面的#xff0c;strcpy 函数容易越界#xff0c;习惯使用 strncpy 函数#xff0c;但此函数只管复制最多 n 个字符为方便以后能够把精力放在应用逻辑上而不在发明轮子上把一些常用的代码片段列于此。首先是字符串处理方面的strcpy 函数容易越界习惯使用 strncpy 函数但此函数只管复制最多 n 个字符并不会把末尾的字符自动修改为 \0所以给它加上这个操作char* utils_strncpy (char *dest, const char *src, size_t length){strncpy (dest, src, length);dest[length] \0;return dest;} 内存分配函数 malloc 分配内存却不进行初始化给它也加上初始化的操作void* utils_malloc (size_t size){void *ptr malloc (size);if (ptr ! NULL)memset (ptr, 0, size);return ptr;} 内存释放函数 free 只是释放内存却不把指针置为空指针而且对空指针执行 free 也不知道是否安全于是改造如下void utils_free(void **p){if (p NULL || *p NULL)return;free(*p);*p NULL;}相应的有字符串复制函数:char* utils_strdup (const char *ch){char *copy;size_t length;if (ch NULL)return NULL;length strlen (ch);copy (char *) utils_malloc (length 1);if (copyNULL)return NULL;utils_strncpy (copy, ch, length);return copy;}把字符串中的大写字母改为小写:int utils_tolower (char *word){size_t i;size_t len strlen (word);for (i 0; i len - 1; i){if (A word[i] word[i] Z)word[i] word[i] 32;}return 0;} 清除字符串首尾的空白字符(空格,\r,\n,\r)int utils_clrspace (char *word){char *pbeg;char *pend;size_t len;if (word NULL)return -1;if (*word \0)return 0;len strlen (word);pbeg word;while (( *pbeg) || (\r *pbeg) || (\n *pbeg) || (\t *pbeg))pbeg;pend word len - 1;while (( *pend) || (\r *pend) || (\n *pend) || (\t *pend)){pend--;if (pend pbeg){*word \0;return 0;}}/* Add terminating NULL only if weve cleared room for it */if (pend 1 word (len - 1))pend[1] \0;if (pbeg ! word)memmove (word, pbeg, pend - pbeg 2);return 0;}嘎然而止.......