gpt4 book ai didi

c - 将 int 数组分配给结构中的指针

转载 作者:行者123 更新时间:2023-12-01 12:08:11 24 4
gpt4 key购买 nike

我在下面创建了 C 结构。

typedef struct KnightsMartSale {
char firstName[21];
char lastName[21];
int numItemsOnList;
int *itemsPurchased; // array of item numbers
struct KnightsMartSale *next;
} KMSale;

这里可以将 int 数组分配给 int *itemsPurchased 指针吗?如果可能如何打印值?

最佳答案

我会根据要复制到 itemsPurchased 中的数组的大小分配内存并“记住”numItemsOnList 中可能的项目数.

所以假设你有一个给定的整数数组,比方说 myArray , 那么复制和打印的代码如下所示:

typedef struct KnightsMartSale {
char firstName[21];
char lastName[21];
int numItemsOnList;
int *itemsPurchased; // array of item numbers
struct KnightsMartSale *next;
} KMSale;

int main() {

KMSale kmsale;

int myArray[] = { 20,30,40,50 };

kmsale.numItemsOnList = sizeof(myArray)/sizeof(myArray[0]);
kmsale.itemsPurchased = calloc(kmsale.numItemsOnList,sizeof(int));
memcpy(kmsale.itemsPurchased,myArray,kmsale.numItemsOnList*sizeof(int));

for (int i=0; i<kmsale.numItemsOnList; i++) {
printf("item #%d: %d\n",i,kmsale.itemsPurchased[i]);
}


// kmsale not needed any more, free memory:
free(kmsale.itemsPurchased);
}

输出:

item #0: 20
item #1: 30
item #2: 40
item #3: 50

关于c - 将 int 数组分配给结构中的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54590258/

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