简体   繁体   中英

Inserting 1D array to 2D array

Can we directly insert a 1D array to a 2D array?

For example I have this code:

void insert(int[]data , int**collection)
{
collection[1] = data
}
int main()
{
int data[2]= {1,3}
int collection[2][2];
insert(data,&collection);
}

Will this work?

You cannot insert a 1D array to 2D array the way you are doing. Use memcpy to copy the elements of 1D array to 2D array, like this:

memcpy(collection[1], data, 2 * sizeof(int));

this will copy the 2 integer elements of data array to collection[1] .

Besides, a couple of problems in your code. Lets discuss them:

First:

insert(data,&collection);
            ^

You don't need to pass the address of collection . Note that, an array, when used in an expression, will convert to pointer to its first element (there are few exceptions to this rule). That means, when you pass collection , it will convert to type int (*)[2] . Just do:

insert(data, collection);

Second:

void insert(int[]data , int**collection)

int[]data is wrong. The first parameter of insert() should be int data[2] or int data[] , both are equivalent to int * data . You can use either of them.

The second argument to insert() is collection array which is a 2D array of integers. When you pass it to insert() , it will decay to pointer whose type is int (*)[2] . The type of second parameter of insert() is int ** which is not compatible with the argument that you are passing to insert() function. The second parameter of insert() function should be int collection[2][2] or int collection[][2] , both are equivalent to int (*collection)[2] .

Putting these altogether, you can do:

#include <stdio.h>
#include <string.h>

#define ROW 2
#define COL 2

void insert(int data[ROW], int collection[ROW][COL]) {
    //for demonstration purpose, copying elements of data array 
    //to all elements (1D array) of collection array.
    for (int i = 0; i < ROW; ++i) {
        memcpy(collection[i], data, COL * sizeof(int));
    }
}

int main(void) {
    int data[COL] = {1, 3};
    int collection[ROW][COL];

    insert(data, collection);

    for (int i = 0; i < 2; ++i) {
        for (int j = 0; j < 2; ++j) {
            printf("collection[%d][%d] : %d ", i, j, collection[i][j]);
        }
        printf("\n");
    }

    return 0;
}

Output:

# ./a.out
collection[0][0] : 1 collection[0][1] : 3 
collection[1][0] : 1 collection[1][1] : 3 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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