简体   繁体   English

将二维数组分配给结构对象

[英]Assigning 2-dimensional array to struct object

I have 2-dimensional array. 我有二维数组。 I want that array to be assigned to struct. 我希望将该数组分配给struct。 Please take a look: 请看一下:

This is my struct: 这是我的结构:

typedef struct {
    int x;
    int y;
    char **table; //2-dim array
} some_struct;

And I want to be able to assign this: 我希望能够分配此:

const char sth1_table[2][3] = {
   { ' ', 'x', ' '},
   { 'x', 'x', 'x'},
};

or this: 或这个:

const char sth2_table[4][2] = {
   { 'x', ' '},
   { 'x', ' '},
   { 'x', ' '},
   { 'x', 'x'},
};

to that struct. 那个结构。

How to do that? 怎么做? I tried assigning: 我尝试分配:

new_sth.table = malloc(sizeof(sth1_table));
*new_sth.table = sth1_table;

And then accessing: 然后访问:

some_struct get_sth;
get_sth = *(some_struct+i);
other_array[a][b] = get_sth.table[a][b];

But with no luck. 但是没有运气。

What am I doing wrong? 我究竟做错了什么?

For starters the member table is not a two dimensional array. 首先,成员table不是二维数组。 It is a pointer. 它是一个指针。

Arrays do not have the assignment operator. 数组没有赋值运算符。 You have to copy arrays element by element. 您必须逐元素复制数组。

For example if you have an object of the structure 例如,如果您具有结构的对象

typedef struct {
    int x;
    int y;
    char **table; // pointer
} some_struct;

some_struct obj;

and array 和数组

const char sth1_table[2][3] = {
   { ' ', 'x', ' '},
   { 'x', 'x', 'x'},
};

then you can make the following way 那么您可以通过以下方式

obj.table = malloc( sizeof( char *[2] ) );

for ( size_t i = 0; i < 2; i++ )
{
    obj.table[i] = malloc( sizeof( sth1_table[i] ) );
    memcpy( obj.table[i], sth1_table[i], sizeof( sth1_table[i] ) );
} 

You should remember that you have to free all allocated memory or realloc it when you need to use another two-dimensional array as an initializer. 您应该记住,当您需要使用另一个二维数组作为初始化程序时,必须释放所有分配的内存或重新分配它。

If you can do it with the array sizes hard coded and without using malloc, I would consider this example: 如果您可以使用硬编码的数组大小而不使用malloc做到这一点,那么我将考虑以下示例:

#include <stdio.h>
#include <stdlib.h>

struct Some_Struct
{
    int x;
    int y;
    char sth1_table[2][3];
    char sth2_table[4][4];
};

int main ( int argc, char *argv[] )
{
    struct Some_Struct yy;
    struct Some_Struct zz[10];

    yy.x = 1;
    yy.y = 2;

    /*
    you wanted this
    const char sth1_table[2][3] = {
        { ' ', 'a', ' '},
        { 'b', 'c', 'd'},
    };
    */

    yy.sth1_table[0][0] = '\0';   /* null character */
    yy.sth1_table[0][1] = 'a';
    yy.sth1_table[0][2] = '\0';
    yy.sth1_table[1][0] = 'b';
    yy.sth1_table[1][1] = 'c';
    yy.sth1_table[1][2] = 'd';

    for ( i = 0; i < 10; i++ )
    {
        zz[i].sth1_table[0][0] = '\0';   /* null character */
        zz[i].sth1_table[0][1] = 'a';
        zz[i].sth1_table[0][2] = '\0';
        zz[i].sth1_table[1][0] = 'b';
        zz[i].sth1_table[1][1] = 'c';
        zz[i].sth1_table[1][2] = 'd';
    }
}

if you are interested in runtime allocation then also consider the calloc() function in addition to malloc(). 如果您对运行时分配感兴趣,那么除了malloc()之外,还要考虑calloc()函数。 When doing so, remember the memory allocation of your 2-d array (or 3-d, 4-d, any-dimension) is just a chunk of memory whose size is the number of dimensions multiplied by the type size. 这样做时,请记住2维数组(或3维,4维,任意维)的内存分配只是一块内存,其大小是维数乘以类型大小。

char sth1_table[2][3];

the size of char is 1 byte. char的大小为1个字节。 1 byte * 2 * 3 = 6 bytes of memory for sth1_table 1个字节* 2 * 3 = sth1_table的6个字节的内存

char sth2_table[4][4];

1 byte * 4 * 4 = 16 bytes of memory sth2_table 1个字节* 4 * 4 = 16个字节的存储器sth2_table

How you then chose to order your data within that allocated memory, whether it is row first or column first, is entirely up to you. 然后,如何选择在已分配内存中排序数据的方式(无论是行第一还是列第一)完全取决于您。

Instead of using malloc directly I suggest defining a macro for memory allocation. 建议不要为内存分配定义一个宏,而不是直接使用malloc This makes the code easier to follow. 这使代码更易于遵循。 In the example below I have taken the liberty to rename some identifiers. 在下面的示例中,我可以随意重命名一些标识符。

#include <stdio.h>
#include <stdlib.h>

#define LEN(arr) (sizeof (arr) / sizeof (arr)[0])

#define NEW_ARRAY(ptr, n) (ptr) = malloc((n) * sizeof (ptr)[0])

typedef struct {
    int m;
    int n;
    char **table;
} Matrix;


int main()
{
    const char items[2][3] = {{' ', 'x', ' '}, {'x', 'x', 'x'}};
    Matrix A;
    int i, j;

    A.m = LEN(items);
    A.n = LEN(items[0]);

    /*initialize matrix*/   
    NEW_ARRAY(A.table, A.m);
    for (i = 0; i < A.m; i++) {
        NEW_ARRAY(A.table[i], A.n);
        for (j = 0; j < A.n; j++) {
            A.table[i][j] = items[i][j];
        }
    }

    /*print matrix*/
    for (i = 0; i < A.m; i++) {
        for (j = 0; j < A.n; j++) {
            printf("%c ", A.table[i][j]);
        }
        putchar('\n');
    }

    return 0 ;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM