0

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;
}
fedi
  • 368
  • 3
  • 7
  • 18
  • 2
    [Please see this discussion on why not to cast the return value of `malloc()` and family in `C`.](http://stackoverflow.com/q/605845/2173917). – Sourav Ghosh Mar 19 '16 at 07:50

1 Answers1

0

You are not copying all the values. The second version works because the pointer is pointing the the array in main() so you are essentialy printing that array, i.e. nums.

To copy all the values, you need to use numsSize and multiply by the size of every element, note that memcpy() copies numsSize bytes. And you array is numsSize * sizeof(initStruct->nums[0]) bytes in size so just change the memcpy() to

memcpy(initStruct->nums, nums, numsSize * sizeof(nums[0]));
Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97