我有以下 struct :
struct NumArray {
size_t size;
int* data;
};
然后,我编写了这个函数来从一个公共数组构建一个"NumArray":
struct NumArray* CreateNumArray(const int* nums, const size_t size) {
struct NumArray* numarray = malloc(sizeof(struct NumArray));
if (numarray == NULL) {
return NULL;
}
numarray->data = malloc(size * sizeof(int));
if (numarray->data == NULL) {
free(numarray);
return NULL;
}
numarray->size = size;
memcpy(numarray->data, nums, size);
return numarray;
}
但当我测试它时,似乎我复制了错误的信息:
int main(void) {
int sample[] = { 1, 2, 3, 4 };
struct NumArray* arr = CreateNumArray(sample, sizeof(sample) / sizeof(sample[0]));
if (arr == NULL) {
return 1;
}
for (size_t idx = 0; idx < arr->size; ++idx) {
printf("%d ", arr->data[idx]);
}
printf("\n");
return 0;
}
Output:
1 476 338297168 476
有人能帮我找到错误吗?
注意:我使用的是gcc 11.2.0