C 初始化结构中的数组
我正在写一个函数初始化结构中的数组, 这是我的结构:C 初始化结构中的数组,c,arrays,struct,C,Arrays,Struct,我正在写一个函数初始化结构中的数组, 这是我的结构: struct NumArray { int numSize; int *nums; }; am用于初始化NumArray实例的函数如下所示: struct NumArray* NumArrayCreate(int* nums, int numsSize) { struct NumArray* initStruct =(struct NumArray*)malloc(sizeof(struct NumArray)); initStruct
struct NumArray {
int numSize;
int *nums;
};
am用于初始化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;
}
您没有复制所有的值。第二个版本可以工作,因为指针指向
main()
中的数组,所以您基本上是在打印该数组,即nums
要复制所有值,需要使用numsize
并乘以每个元素的大小,注意memcpy()
复制numsize
字节。数组的大小是numsize*sizeof(initStruct->nums[0])
字节,所以只需将memcpy()
更改为
memcpy(initStruct->nums, nums, numsSize * sizeof(nums[0]));
是的,我的天Baaad@fedi在使用指针之前,请始终检查
malloc()
是否未返回NULL
,并删除那些丑陋的强制转换,因为它们不是必需的。