c - 将具有固定长度字符串的数组传递给 C 中的函数

标签 c arrays string function size

我试图让程序启动一个单独的进程,该进程仅列出 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/

相关文章:

c - 初始化程序元素不是常量 - 在循环内使用静态变量

计算单词的平均长度(不够精确)

c++ - 如何使用 libgit2 提交到 git 存储库?

c - fscanf == 1 做什么

ruby - 使用正则表达式返回字符串的前缀,其中剥离的字符串有时包含 '/'

php - 如何使用 id 获取多个值并将其存储在变量中

Javascript数组字符串到正则表达式文字

php - 将键添加到数组 PHP 中尚无键的值

string - 如何从 Golang Strings.Builder 对象中修剪最后一个字符?

c - 垃圾值;奇怪的字符串 strlen 值