在我的 main 中,我定义了一个指向文件名字符串数组(待定)的指针:
char **commands = NULL;
然后我调用一个函数,该函数使用 getopt()
根据 argc
和 argv
填充数组。在我从函数返回之前,我打印了数组中的文件列表,它工作正常。
回到我的主界面,我尝试打印相同的列表(作为确认),但我收到一个段错误,我不知道如何修复。我在下面包含了我的代码。
谁能帮我理解为什么我的 main 中的 commands
无法访问文件列表。
干杯,
午睡
这是构建文件名列表的函数:
int getInput (int argc, char **argv, const char *optionList, int *number, int *showEnds, char **commands, int *numberCommands) {
char c;
opterr = 0; // Turn off automatic error messages.
while ( (c = getopt(argc, argv, optionList)) != -1) {
switch (c) {
case 'n':
*number = TRUE;
break;
case 'E':
*showEnds = TRUE;
break;
case '?':
printf("Invalid switch used \"%c\"\n", optopt);
return EXIT_FAILURE;
break;
default:
printf("Input error occurred");
return EXIT_FAILURE;
}
}
printf("optind = %d,%d\n",optind, argc);
commands = malloc(sizeof(char*) * (argc-1));
if (optind < argc) {
*numberCommands = (argc - optind);
int ndx = 1;
while (optind < argc) {
int arraySize = (ndx+1)*sizeof(char*);
commands = realloc (commands,arraySize);
if (commands == NULL) {
fprintf(stderr,"Realloc unsuccessful");
exit(EXIT_FAILURE);
}
int stringSize = strlen(argv[optind])+1;
commands[ndx] = malloc(stringSize);
if(commands[ndx]==NULL){
fprintf(stderr,"Malloc unsuccessful");
exit(EXIT_FAILURE);
}
strcpy(commands[ndx],argv[optind]);
ndx++;
optind++;
}
printf ("Done With Input\n");
for (int i=1; i<=*numberCommands; i++) {
printf ("%s\n",commands[i]);
}
}
return EXIT_SUCCESS;
}
这是我的主要内容:
int main(int argc, char **argv) {
FILE *myInput;
FILE *myOutput;
int result;
const char availOptions[] = "nE";
// Option flags
int number = FALSE; // (Option n) number all output lines
int showEnds = FALSE; // (Option E) Show Ends
char **commands = NULL;
int numberCommands = 0;
// Set default to stdin/stdout.
myInput = stdin;
myOutput = stdout;
if (argc > 1) {
result = getInput(argc,argv, availOptions, &number, &showEnds, commands, &numberCommands);
if (result != EXIT_SUCCESS) {
exit(EXIT_FAILURE);
}
}
printf ("Number of files = %d\n", numberCommands);
for (int i=1; i<=numberCommands; i++) {
printf ("%s\n",commands[i]);
}
echoInput(myInput, myOutput);
}
最佳答案
您正在传递双指针的副本
char **commands;
进入函数。当您为它malloc()
内存时,它不会更新主函数中的指针,只会更新双指针的本地副本。因此,您试图在 main 中引用 NULL 指针。您可以改为传递一个指向双指针的指针(即函数将采用三指针),这样您的代码就可以工作了。
您需要像这样取消引用函数内的三重指针:
*commands = malloc(sizeof(char*) * (argc-1));
或者,在你的函数中创建一个新的双指针,完成你的工作(大致保持函数中的代码原样),然后在你返回之前,将内存分配回从 main 传入的指针:
*commands = local_commands;
关于c - 访问由 C 中的函数修改的字符串数组时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22452891/