在struct中初始化数组

时间:2017-12-06 18:09:19

标签: c arrays struct

我尝试初始化结构中的数组Like this

我希望数组的大小为row * col。

以下是代码的一部分:

struct tbl{
    int col;
    int row;
    char** elem [col*row];
};


int main(int argc, char** argv){

    int i, row, col;
    col = row = 0;
    bool loop = true;
    char c;     
    col = col/row;  

    table tab;
    tab.row = row;
    tab.col = col;

    return 0;
}

3 个答案:

答案 0 :(得分:0)

请注意

  • 您无法在代码中预设row col的值。

要实现这一点,您需要像这样的动态分配

struct matrix {
    int row_count;
    int col_count;
    int **values;
};

void free_matrix(struct matrix *const M);
int initialize_matrix(struct matrix *const M, int row_count, int col_count);

int initialize_matrix(struct matrix *const M, int row_count, int col_count)
{
    M->values = malloc(sizeof *M->values * row_count);
    if (M->values == NULL)
        return -1;
    M->row_count = 0;
    for (int row = 0; row < row_count; ++row) {
        M->values[row] = malloc(sizeof **M->values * col_count);
        // In case of failure to allocate
        // free all rows.
        if (M->values[row] == NULL) {
            free_matrix(M);
        } else {
            M->row_count += 1;
        }
    }
    M->col_count = col_count;
}

void free_matrix(struct matrix *const M)
{
    if (M == NULL)
        return;
    for (int row = 0; row < M->row_count; ++row) {
        free(M->values[row]);
    }
    free(M->values);
}

int main(void)
{
    struct matrix M;
    initialize_matrix(&M);
    // Use the matrix here
    free_matrix(&M);
}

使用malloc()free()时,您应该非常小心,必须正确使用它,否则您的程序会发生意外情况。

答案 1 :(得分:0)

您不能以这种方式声明结构。人们做的一件事是将它们的数组设置到结构的末尾,然后使用malloc为结构中的数组留出额外的空间。像这样:

typedef struct {
    int row;
    int col;
    char **elem[];
} table;

void some_func() {
    int row = 5;
    int col = 5;
    table *tab = malloc(sizeof(table) + ((row * col) * sizeof(char **)));
    tab->row = row;
    tab->col = col;
    // now do whatever you need to with your new struct
    // that holds an array of 25 char ** elements
}

答案 2 :(得分:0)

代码中的错误很少。您可能想要下面发布的内容。另外,不要除以零。

struct tbl{
    int col;
    int row;
    // char** elem [col*row]; // can't initialize array size this way
    char** elem;
};


int main(int argc, char** argv){

    int i, row, col;
    col = row = 0;
    bool loop = true;
    char c;           // Unused?      
    col = col/row;    // zero divided by zero? You sure you want that?   

    // table tab;        // not defined correctly, Use next line instead 
    struct tbl tab;   
    tab.row = row;
    tab.col = col;

    tab.elem = malloc(sizeof(char*)*tab.row);
    for (i=0 ; i<tab.row ; i++) {
        tab.elem[i] = malloc(sizeof(char)*tab.col);
        /* initalize tab.elem[i] */
    }

    /* ... do stuff */

    // free memory
    for (i=0 ; i<tab.row ; i++) {
        free(tab.elem[i]);
    }
    free(tab.elem);

    return 0;
}