c - 将结构定义放在函数原型(prototype)之前,但结构需要来自 argv 的信息

标签 c struct prototype

我有一个结构定义,需要由多个不同的函数使用。在我的结构定义中,我有一个大小为“len”的数组,这个 len 变量是 argv[1] 中字符串的长度。如您所见,我需要这个变量,但我不能将结构定义放在 main 之外,否则我会丢失该变量。但我确实需要将它放在我的一个函数的原型(prototype)之前。这个问题的解决方案是什么?这是我的代码:

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;

最佳答案

结构需要具有一致的编译时定义才能以这种方式使用。您最好使用指针而不是静态数组并为数组动态分配空间。然后,您需要将长度作为结构的一部分。

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);

    ...

}

关于c - 将结构定义放在函数原型(prototype)之前,但结构需要来自 argv 的信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37818869/

相关文章:

以枚举值作为参数的 Javascript 构造函数

c - 如何在不使用内置 printf 函数的情况下在 C 中的屏幕上显示消息?

c - 指向像数组一样使用索引访问的结构的指针

c 代码输出意外/预期的行为

定义结构时的 C 特殊语法(添加 ':' )

c - 为结构内部的指针赋值

javascript - 方法作为原型(prototype)中的属性

javascript - 如果更改构造函数的原型(prototype),为什么对象的构造函数属性会更改?

C regex.h 最短匹配

c++ - 为什么*ptr在printf中?