簡體   English   中英

在使用相同的 function 和變量時,C 中的指針取消引用失敗

[英]Failure in Pointer Dereferencing in C while using same function and variable

我正在嘗試使用 C 來處理具有不同擴展名的文件。 所以這是我寫的代碼。

#include <stdio.h>
#include <windows.h>
#include <unistd.h>
#include <conio.h>

void mvjpg(char *arg);
void mvpng(char *arg);
void wincmd(const char *c,...);

int main(int argc,char **argv){
   char *ext;

   for(int i=1;i<argc;i++){
       ext=strrchr(argv[i],'.');
       if(ext == NULL)
           continue;

       if(strcmp(ext,".jpg")==0)
            mvjpg(argv[i]);

       if(strcmp(ext,".png")==0)
            mvpng(argv[i]);
   }

   return 0;
}

void mvjpg(char *arg){

//Do tasks such as ...
    wincmd("move %s Done\\ ",arg);  //Here this runs properly
    printf("%s\n\n",arg);           //This also outputs the file name
    wincmd("copy %s JPGs\\ ",arg);  //Here the value is gibberish
    printf("%s\n\n",arg);           //This too outputs the file name
   

}

void mvpng(char *arg){
     //Do tasks such as ...
}


void wincmd(const char *c,...){
    char cmd[50];
    sprintf(cmd,c);
    printf("%s\n",cmd);
    system(cmd);
}

Output 是:

D:\Folder1>mv new.jpg
move new.jpg Done\
        1 file(s) moved.
new.jpg

copy 6Q½6ⁿ JPGs\
The system cannot find the file specified.
new.jpg

為什么一個指針在第一個工作而在另一個不是。 指針的值在這些命令之間沒有改變。

目前尚不清楚您為什么使用可變參數列表。

像這樣聲明 function 會簡單得多

void wincmd( const char *fmt, const char *s );

並在 function 內寫入

sprintf( cmd, fmt, s);

不過這個電話

sprintf(cmd,c);

調用未定義的行為,因為沒有指定對應於字符串c中存在的轉換規范&s的第三個參數。

您需要包含 header <stdarg.h> ,它旨在處理可變參數列表並使用 header 中定義的宏處理未命名參數。

這是一個演示程序。

#include <stdio.h>
#include <stdarg.h>

void wincmd( const char *c, ... ) {
    char cmd[50];

    va_list arg;

    va_start( arg, c );

    const char *p = va_arg( arg, const char *);

    sprintf( cmd, c, p );

    va_end( arg );

    puts( cmd );
}

int main( void )
{
    const char *s = "move %s Done\\ ";
    const char *t = "new.jpg";

    wincmd( s, t );

    s = "copy %s JPGs\\ ";

    wincmd( s, t );
}

程序 output 是

move new.jpg Done\
copy new.jpg JPGs\

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM