2011-12-02 264 views
1

我對這段代碼有很多麻煩(我不擅長指針:P)。所以這裏是代碼。指針指針

printf("\n Enter the file name along with its extensions that you want to delete:-"); 
        scanf("%s",fileName); 
             deletefile_1_arg=fileName; 
             printf("test\n"); 
        result_5 = deletefile_1(&deletefile_1_arg, clnt); 
        if (result_5 == (int *) NULL) { 
         clnt_perror (clnt, "call failed"); 
        } 
        else 
        { 
         printf("\n File is deleted sucessfully"); 
         goto Menu2; 
        } 
        break; 

被調用的函數如下。

int * 
deletefile_1_svc(char **argp, struct svc_req *rqstp) 
{ 
static int result; 
    printf("test2\n"); 
printf("%s",**argp); 
if(remove(**argp)); 
{ 
    printf("\nFile Has Been Deleted"); 
    result=1; 
} 
return &result; 
} 

我在控制檯上得到test2,但是。它不會打印argp的值/刪除該特定文件。我不確定我做錯了什麼。請幫幫我。

+0

下面是可能有用的東西http://boredzo.org/pointers/#dereferencing – Cyclonecode

回答

1

argp是一個指針的指針字符,你要使用它作爲一個字符指針,嘗試更改您的代碼:

printf("%s", *argp); 

您還需要改變你的remove調用:

remove(*argp); 
0

我總是發現畫圖有助於理解指針。使用框來存儲內存地址,框的標籤是變量名。如果該變量是一個指針,那麼該框的內容就是另一個框的地址(畫線到另一個框)。

當您不需要時,您正在使用指針。你的「deletefile1_svc」函數根本不處理「argp」的值,所以它不需要指針指針。加上你的「結果」不需要作爲指針返回,因爲它只是一個數值。您也不會初始化結果(可能爲零)或重新初始化它(它是靜態的,因此它會記住分配給它的最後一個值)。

int 
deletefile_1_svc(const char *argp, struct svc_req *rqstp) 
{ 
    int result = 0; /* Initial value => failure */ 
    if (remove (argp) == 0) 
    { 
     result = 1; /* 1 => success */ 
    } 
    return result; 
} 

要調用該函數使用:

result_5 = deletefile1_svc(filename, clnt); 
if (result_5 == 0) 
    // Failed 
else 
    // Success 

這將使得代碼更簡單,更容易出現錯誤。

+0

我正在使用rpcgen。所有變量和方法都是自動生成的。無法更改它們。 – slonkar