初始化结构中的数组

时间:2016-03-19 07:46:26

标签: c arrays struct

我正在编写一个初始化结构内部数组的函数, 这是我的结构:

struct NumArray {
int numSize;
int *nums;
};

用于初始化NumArray实例的函数如下:

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

在main中调用这个函数给了我奇怪的值:

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

使用第二个版本,我得到了预期的值,但我想知道为什么第一个版本不能工作,这是第二个版本:

struct NumArray* NumArrayCreate(int* nums, int numsSize)
{
 struct NumArray* initStruct =(struct NumArray*)malloc(sizeof(struct NumArray));

 initStruct->numSize = numsSize;
 initStruct->nums = nums;

 return initStruct;
}

1 个答案:

答案 0 :(得分:0)

您没有复制所有值。第二个版本有效,因为指针指向main()中的数组,因此您必须打印该数组,即nums

要复制所有值,您需要使用numsSize并乘以每个元素的大小,请注意memcpy()复制numsSize个字节。并且您的数组大小为numsSize * sizeof(initStruct->nums[0])个字节,因此只需将memcpy()更改为

即可
memcpy(initStruct->nums, nums, numsSize * sizeof(nums[0]));
相关问题