Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/63.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 初始化结构中的数组_C_Arrays_Struct - Fatal编程技术网

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
,并删除那些丑陋的强制转换,因为它们不是必需的。