提问人:Sammy1410 提问时间:11/24/2022 最后编辑:Vlad from MoscowSammy1410 更新时间:11/24/2022 访问量:35
使用相同函数和变量时,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);
}
输出为:
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
为什么一个指针首先起作用,而在另一个指针中则不然。指针的值在这些命令之间不会更改。
答:
1赞
Vlad from Moscow
11/24/2022
#1
目前尚不清楚为什么要使用变量参数列表。
声明函数会简单得多,例如
void wincmd( const char *fmt, const char *s );
并在函数内写入
sprintf( cmd, fmt, s);
尽管如此,这个电话
sprintf(cmd,c);
调用未定义的行为,因为未指定与字符串中存在的转换规范相对应的第三个参数。&s
c
您需要包含旨在处理变量参数列表的标头,并使用标头中定义的宏处理未命名的参数。<stdarg.h>
这是一个演示程序。
#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 );
}
程序输出为
move new.jpg Done\
copy new.jpg JPGs\
评论
vsprintf()
sprintf()
wincmd()