我试图让程序启动一个单独的进程,该进程仅列出 Linux 中的长格式文件。 (换句话说,我试图让我的程序执行“ls -al”)。我遇到的问题是编译器不断警告我以下消息:警告:从不兼容的指针类型传递参数 2 of 'run'
如何解决这个问题?
#include <sys/types.h>
#include <sys/stat.h>
#include <wait.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
void run(char *app,char* param[250]){
if (fork()==0){
execvp(app,param);
}else{
wait(NULL);
}
}
int main(){
printf("Running ls -al...\n");
char param[10][250];
strcpy(param[0],"ls");
strcpy(param[1],"-al");
param[2][0]='\0';
run("/usr/bin/ls",param);
printf("\n");
return 0;
}
最佳答案
代码中还有其他错误:
此表达式:char* param[250]
(run()
函数的第二个参数)
表示该参数是一个指向由 250 个字符数组指针组成的数组的指针。
这是不正确的。
表达式应为:char * param[]
如果回到 main() 中将参数定义为:
char ** param = NULL;
然后在检查错误的同时分配适当数量的内存
if( NULL == (param = malloc( 3* sizeof (char*) ) )
{ // then malloc failed
perror( "malloc for array of parameters failed" );
exit( EXIT_FAILURE );
}
// implied else, malloc successful
然后是参数值和参数列表终止符:
param[0] = "ls"; // sets a pointer
param[1] = "-al"; // sets a pointer
param[2] = NULL;
关于c - 将具有固定长度字符串的数组传递给 C 中的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33225566/