I'am writng a function that initialise an array inside a structure, This is my structure :
struct NumArray {
int numSize;
int *nums;
};
the function am using to initialize a NumArray instance is as follow:
struct NumArray* NumArrayCreate(int* nums, int numsSize)
{
struct NumArray* initStruct =(struct NumArray*)malloc(sizeof(struct NumArray));
initStruct->nums =(int*)malloc (sizeof(int)*numsSize);
initStruct->numSize = numsSize;
memcpy (initStruct->nums, nums, numsSize);
return initStruct;
}
Calling this function in the main gives me weird values:
int nums[5] = {9,2,3,4,5};
int main ()
{
struct NumArray* numArray = NumArrayCreate(nums, 5);
printf ("%i\n",numArray->nums[0]);
printf ("%i\n",numArray->nums[1]);
printf ("%i\n",numArray->nums[2]);
printf ("%i\n",numArray->nums[3]);
}
using a 2nd version, i get the expected values, but i am wondering why the first version won't work, this is the 2nd version:
struct NumArray* NumArrayCreate(int* nums, int numsSize)
{
struct NumArray* initStruct =(struct NumArray*)malloc(sizeof(struct NumArray));
initStruct->numSize = numsSize;
initStruct->nums = nums;
return initStruct;
}