简体   繁体   中英

How to initialize an int pointer inside a struct assingning it to an array in C?

I've got a struct to say:

struct mystruct {
       int *myarray;
}

In my main function, I want to assign to "myarray" the values of a predefined array.

int main(){
   int array[5] = {1,2,3,4,5};
   //how to "assign" array values to myarray ?;
}

I would like avoid making a cycle of an assignment like :

struct mystruct str = malloc(sizeof(mystruct));
for(int i = 0;i<size_of_array;i++){
    str->myarray[i] = array[i];
}

is this possible?

struct mystruct {
       int *myarray;
}

here myarray is just a pointer to memory. There is no space reserved there, so your example will fail.

You have two options:

  1. Just use the array you already have, this assumes the array is not free'd before the structure is free'd:

    instance->myarray = array;

  2. reserve memory and memcpy the data

     instance->myarray = malloc(sizeof(int) * 5); memcpy(instance->myarray, array, sizeof(int) * 5); 

you can try memcpy

struct->array = malloc(sizeof(some_array));
memcpy(struct->array, some_array, sizeof(some_array));

and for your case this is

   str->array = malloc(sizeof(array));
   memcpy(str->array, array, sizeof(array));

Consider:

typedef struct test
{
    int i;
    char c[2][5];
} test;

This can be initialized using:

test t = {10, {{'a','b','c','d','\0'}, { 0 }}};
// or
test t = {10, {{'a','b','c','d','\0'}, {'x','y','z','v','\0'}}};

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