作者hardman1110 (硬漢)
看板C_and_CPP
標題[問題] 雙重指標
時間Wed Feb 18 21:08:07 2009
#include <stdio.h>
#include <string.h>
void input(FILE **pfp1, FILE **pfp2)
{
char string[20];
printf("請輸入文章檔名:");
gets(string);
*pfp1 = fopen(string,"r");
printf("輸入測試的字串:");
gets(string);
*pfp2 = fopen(string,"r");
}
void output(int count)
{
printf("出現了%d次\n",count);
}
int process(FILE *fp1, FILE *fp2)
{
int count=0;
char st[20], word[20];
fscanf(fp2,"%s",word);
printf("Searching word=%s\n",word);
while(fscanf(fp1,"%[^., ]",st)!=EOF)
{
if(strcmp(st,word)==0)
{
count++;
}
fscanf(fp1,"%[., ]",st);
}
return count;
}
void main(void)
{
FILE *fp1, *fp2;
int count;
input(&fp1, &fp2);
count=process(fp1, fp2);
output(count);
}
--------------------------------------------------------------------
這個程式目的是在一篇文章中搜尋關鍵字,我想問的是為什麼在input裡要用
**pfp1這種雙重指標? 在process裡開檔就好了不是嗎? 這樣做有什麼用意嗎?
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 114.42.208.139
→ tsaiminghan:這樣做的話, fun沒用全域變數 02/18 21:11
→ tsaiminghan:code比較容易看吧 02/18 21:12
→ tsaiminghan:全域變數用多了, 有時可能會不小心改到蛋是沒注意到 02/18 21:13
→ tsaiminghan:會不好debug 02/18 21:13
→ hardman1110:那改成input(fp1,fp2) 裡面用*pfp1會怎樣? 02/18 21:41
→ tsaiminghan:會得不到值 02/18 21:44
→ tsaiminghan:簡單說, input變數除了要輸入, 也要輸出到變數 02/18 21:46
→ tsaiminghan:所以要用** , 而process變數只要輸入, 所以用* 02/18 21:47
→ tsaiminghan:你好好想一下何謂call by reference, 把過程推演一下 02/18 21:48
→ tsaiminghan:就會知道 02/18 21:48
→ walm20:C++ call by ref不是長這樣 02/18 23:31
→ tsaiminghan:了解, 我搞錯了, 我一直把傳指標的方式當成by r 02/19 00:34