gpt4 book ai didi

c - 使用字符串数组时出现总线错误 10 - C

转载 作者:太空宇宙 更新时间:2023-11-04 03:52:36 25 4
gpt4 key购买 nike

我有一个程序在选项参数(-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

我得到一个总线错误。

最佳答案

添加了一些评论......

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
}

关于c - 使用字符串数组时出现总线错误 10 - C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19557470/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com