#include <stdio.h>
# include <string.h>
# include <stdlib.h>
#include <unistd.h>
int main()
{
int opt;
char *name1,*name2 ;
char *word[3];
word[0] = malloc(sizeof(char)*5);
strcpy(word[0],"file");
strcat(word[0],"\0");
word[1] = malloc(sizeof(char)*5);
strcpy(word[1],"-aram");
strcat(word[1],"\0");
word[2] = malloc(sizeof(char)*5);
strcpy(word[2],"-braj");
strcat(word[2],"\0");
char **words;
words = word;
while((opt = getopt(3,words,"a:b:"))!= -1)
{
switch(opt)
{
case 'a':
name1 = optarg;
break;
case 'b' :
name2 = optarg;
break;
}
}
printf("a %s b %s \n",name1,name2);
return 0;
}
上面的代码工作正常,但是当我在>单独的函数function1中为word分配参数并将指针word传递给另一个双指针word>并将这个指针传递给getopt函数时,它会因段错误而崩溃。
请参阅下面的代码,该代码不起作用。程序在 >getopt 处给出分段错误。
#include <stdio.h>
# include <string.h>
# include <stdlib.h>
#include <unistd.h>
char ** function1()
{
char *word[3];
word[0] = malloc(sizeof(char)*5);
strcpy(word[0],"file");
strcat(word[0],"\0");
word[1] = malloc(sizeof(char)*5);
strcpy(word[1],"-aram");
strcat(word[1],"\0");
word[2] = malloc(sizeof(char)*5);
strcpy(word[2],"-braj");
strcat(word[2],"\0");
return word;
}
int main()
{
int opt;
char *name1,*name2 ;
char **words = function1();
while((opt = getopt(3,words,"a:b:"))!= -1)
{
switch(opt)
{
case 'a':
name1 = optarg;
break;
case 'b' :
name2 = optarg;
break;
default:
break;
}
}
printf("a %s b %s \n",name1,name2);
return 0;
}
请参阅下面的 gdb 调试输出,其中显示单词和单词是相同的。
(gdb) print word $1 = {0x804a008 "file", 0x804a018 "-aram", 0x804a028 "-braj"} (gdb) s 21 } (gdb) s
断点 2, main () at test_getopt.c:30 30 while((opt = getopt(3,words,"a:b:"))!= -1) (gdb) print words $2 = (char **) 0xffffb124 (gdb) print words[0] $3 = 0x804a008 "file" (gdb) print words[1] $4 = 0x804a018 "-aram" (gdb) print words[2] $5 = 0x804a028 "-braj"
有人请告诉我,当我们从另一个函数获取参数指针 > 并将其传递给 getopt 时有什么不同。