我有一个结构定义,需要由多个不同的函数使用。在我的struct定义中,我有一个大小为“len”的数组,这个len变量是argv [1]中字符串的长度。正如您可能看到的,我需要这个变量,但我不能将结构定义放在main之外,否则我会丢失该变量。但我确实需要将它放在我的一个函数的原型之前。这个问题的解决方案是什么?这是我的代码:
void randomize( type_darwin *darwin, type_monkey *monkey );
int main( int argc, char *argv[] )
{
if ( argc < 2 )
{
printf("Error! Arguments are of form: ./%s [string to parse]\nBe sure your string is surrounded by double quotes.\n", argv[0]);
return 0;
}
int len = strlen(argv[1]); // length of string
const char *string = argv[1]; // make string a constant
// define two structs, one for the Darwinian algorithm and one for the monkey bashing algorithm
// lock determines whether that element in sentence is locked (in programming terms, if it should now be a constant)
typedef struct darwin
{
char sentence[len];
int lock[len]; // 0 defines not locked. Nonzero defines locked.
} type_darwin;
typedef struct monkey
{
char sentence[len];
int lock; // 0 defines entire array not locked. Nonzero defines locked.
} type_monkey;
答案 0 :(得分:3)
结构需要具有一致的编译时定义才能以这种方式使用。你最好使用指针而不是静态数组并动态地为数组分配空间。然后,您需要使结构的长度部分。
typedef struct darwin
{
int len;
char *sentence;
int *lock; // 0 defines not locked. Nonzero defines locked.
} type_darwin;
typedef struct monkey
{
int len;
char *sentence;
int lock; // 0 defines entire array not locked. Nonzero defines locked.
} type_monkey;
int main(int argc, char *argv[] )
{
if ( argc < 2 )
{
printf("Error! Arguments are of form: ./%s [string to parse]\nBe sure your string is surrounded by double quotes.\n", argv[0]);
return 0;
}
int len = strlen(argv[1]); // length of string
const char *string = argv[1]; // make string a constant
type_darwin my_darwin;
my_darwin.len = len;
my_darwin.sentence = malloc(len + 1);
my_darwin.lock = malloc((len + 1) * sizeof(int));
type_monkey my_monkey;
my_monkey.len = len;
my_monkey.sentence = malloc(len + 1);
...
}