Reputation: 534
I have a struct definition that will need to be used by multiple different functions. In my struct definition, I have an array that is of size "len" and this len variable is the length of the string in argv[1]. As you might see, I need this variable but I cannot place the struct definition outside of main, or else I lose that variable. But I do need to place it before the prototype of one of my functions. What's the solution to this problem? Here is my code:
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;
Upvotes: 0
Views: 76
Reputation: 223897
The structures need to have a consistent compile-time definition to be used in this fashion. You're better off using pointers instead of static arrays and allocating space for the arrays dynamically. You'd then need to make the length part of the struct.
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);
...
}
Upvotes: 3