gpt4 book ai didi

c - 初始化结构体中的数组

转载 作者:行者123 更新时间:2023-11-30 17:03:38 26 4
gpt4 key购买 nike

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

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

关于c - 初始化结构体中的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36099252/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com