1

我有一个程序在选项参数(-r,-d 等)之后采用非选项参数(从命令行),并将每个非选项参数插入到数组中。可以输入的非选项参数的最大数量是 25。

但问题是当我运行程序时出现“总线错误 10”错误,我不知道为什么。我看过很多有类似问题的帖子,但似乎无法解决我的问题。

代码是:

void loop_namelist(int argc, char *argv[])
{   
int index = 0;
--optind;

char *buff_namelist[25]; //the array that the arguments are stored in
*buff_namelist = malloc(25 * 25); //allocating some memory for the array

while (optind < argc) //loop until no arguments left
{

    strcpy(buff_namelist[index], argv[optind]); 

    ++index; //move to next index in array
}
}

当我这样运行它时:

./program -r arg1 arg2

我得到一个总线错误。

4

2 回答 2

1

添加了一些评论...

char *buff_namelist[25]; //the array that the arguments are stored in

//you don't need to allocate memory for array, but in this case you need to allocate
//memory for each element in array better to do that in for loop
*buff_namelist = malloc(25 * 25); //allocating some memory for the array

while (optind < argc) //loop until no arguments left
{
    //instead of this you should allocate and then copy; or use strdup
    strcpy(buff_namelist[index], argv[optind]); 

    ++index; //move to next index in array
}

正确的代码是:

char *buff_namelist[25]; //the array that the arguments are stored in

while (optind < argc && argc < 25) //loop until no arguments left
{

    buff_namelist[index]= strdup(argv[optind]); 

    ++index; //move to next index in array
    optind++; //or somehow update optind
}
于 2013-10-24T05:18:21.980 回答
0

your code

 char *buff_namelist[25]; // array that the arguments are stored in
 *buff_namelist = malloc(25 * 25); //allocating memory for the array

is completely wrong. At least it should be

 char* buff_namelist[25];
 for (int i=0; i<25; i++) {
   char* p = malloc(100);
   if (!p) { perror("malloc"); exit(EXIT_FAILURE); };
    buff_name[i] = p;
 }

but even the above is probably wrong. Perhaps you want to use strdup.

And most importantly if the argv is the second argument to main you can copy the pointers in it (don't need to copy the string contents) like buf_name[i] = argv[optind+i];

于 2013-10-24T05:20:19.397 回答