我正在编写一个函数来初始化结构内部的数组,这是我的结构:
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;
}
在主体中调用此函数会给我怪异的值:
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;
}
您没有复制所有值。第二个版本有效,因为指针指向该数组,main()
因此您必须打印该数组,即nums
。
要复制所有值,需要使用numsSize
并乘以每个元素的大小,请注意要memcpy()
复制numsSize
字节。而且您的数组numsSize * sizeof(initStruct->nums[0])
大小为字节,因此只需将更memcpy()
改为
memcpy(initStruct->nums, nums, numsSize * sizeof(nums[0]));
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句