Adl
Adl

Reputation: 137

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?

Upvotes: 0

Views: 88

Answers (3)

Shakil
Shakil

Reputation: 4630

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

Upvotes: 0

Umer Arif
Umer Arif

Reputation: 255

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'}}};

Upvotes: 0

RedX
RedX

Reputation: 15184

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

Upvotes: 1

Related Questions