c言語中細節留意(初級)。本站提示廣大學習愛好者:(c言語中細節留意(初級))文章只能為提供參考,不一定能成為您想要的結果。以下是c言語中細節留意(初級)正文
1 /*
2 編寫如下函數,不運用下標運算符,前往字符串str中字符c的個數
3 (若不存在則為0)。
4 */
5
6 #include <stdio.h>
7
8 int str_chnum(const char *str, char c)
9 {
10 int n = 0;
11
12 while (*str) {
13 if (c == *str++) n++;
14 }
15 return (n);
16 }
17
18 int main(void)
19 {
20 char str[100];
21 char c;
22
23 printf("請輸出字符串:"); scanf("%s", str);
24
25 getchar(); // 肅清緩存
26
27 printf("請輸出要查找的字符:"); scanf("%c", &c);
28
29 printf("\n字符串\"%s\"中含有%d個字符\'%c\'。\n", str, str_chnum(str, c), c);
30
31 return (0);
32 }
stack overflow景象,自己用的gcc版本為
gcc 版本 4.4.7 20120313 (Red Hat 4.4.7-4) (GCC)
1 /*
2 不運用下標運算符,寫出與代碼清單9-13中的str_toupper函數
3 和str_tolower函數功用相反的函數。
4
5 */
6
7 #include <ctype.h>
8 #include <stdio.h>
9
10 // 將字符串中的英文字符轉換為大寫字母
11 void str_toupper(char *str)
12 {
13 while (*str)
14 *str = toupper(*str++);
15 }
16 //運用valgrind後呈現內存overflow
假如改成如下代碼則正常
1 char *str_toupper(char *str)
2 {
3 char *p = str;
4 while(*str) {
5 *str = toupper(*str);
6 *str++;
7 }
8 return p;
9 }